Servlet 起航 文件上传 中文文件名下载

 23 @WebServlet(name = "ticketServlet",urlPatterns = {"/tickets"},loadOnStartup = 1)
 24 @MultipartConfig(fileSizeThreshold = 5242880,
 25 maxFileSize = 20971520L,//20MB
 26 maxRequestSize = 41943040L//40MB
 27 )
 28 public class TicketServlet extends HttpServlet{
 29     //线程可见性
 30     private volatile int TICKET_ID_SEQUENCE = 1;
 31     private Map<Integer,Ticket> ticketDatabase = new LinkedHashMap<>();
 32 
 33     @Override
 34     protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
 35        //使用请求参数做了一个菜单
 36         String action = req.getParameter("action");
 37         if (action == null){
 38             action = "list";//默认ticket列表
 39         }
 40         switch (action){
 41             case "create":
 42                 this.showTicketForm(resp);//展示表单
 43                 break;
 44             case "view":
 45                 this.viewTicket(req,resp);//具体一张
 46                 break;
 47             case  "download":
 48                 this.downloadAttachment(req,resp);//下载附件
 49                 break;
 50             default:
 51                 this.listTickets(resp);//展示ticket
 52                 break;
 53         }
 54     }
 55 
 56     @Override
 57     protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
 58         String action = req.getParameter("action");
 59         if(action == null){
 60             action = "list";
 61         }
 62         switch (action){
 63             case "create":
 64                 this.createTicket(req,resp);//表单提交实际创建方法
 65                 break;
 66             case "list":
 67             default:
 68                 resp.sendRedirect("tickets");//重定向 get
 69                 break;
 70 
 71         }
 72 
 73     }
 74 
 75 
 76     private void listTickets(HttpServletResponse response) throws IOException {
 77         PrintWriter writer = this.writeHeader(response);
 78 
 79         writer.append("<h2>Tickets</h2>\r\n");
 80         //createTicket入口 先展示一个表单
 81         writer.append("<a href=\"tickets?action=create\">Create Ticket")
 82                 .append("</a><br/><br/>\r\n");
 83 
 84         if(this.ticketDatabase.size() == 0)
 85             writer.append("<i>There are no tickets in the system.</i>\r\n");
 86         else
 87         {
 88             for(int id : this.ticketDatabase.keySet())
 89             {
 90                 String idString = Integer.toString(id);
 91                 Ticket ticket = this.ticketDatabase.get(id);
 92                 writer.append("Ticket #").append(idString)
 93                         .append(": <a href=\"tickets?action=view&ticketId=")
 94                         .append(idString).append("\">").append(ticket.getSubject())
 95                         .append("</a> (customer: ").append(ticket.getCustomerName())
 96                         .append(")<br/>\r\n");
 97             }
 98         }
 99 
100         this.writeFooter(writer);
101     }
102 
103     private void viewTicket(HttpServletRequest request, HttpServletResponse response) throws IOException {
104         //从ticket列表进入某张ticket所需要id
105         String idString = request.getParameter("ticketId");
106         Ticket ticket = this.getTicket(idString, response);
107         if(ticket == null)
108             return;
109 
110         PrintWriter writer = this.writeHeader(response);
111 
112         writer.append("<h2>Ticket #").append(idString)
113                 .append(": ").append(ticket.getSubject()).append("</h2>\r\n");
114         writer.append("<i>Customer Name - ").append(ticket.getCustomerName())
115                 .append("</i><br/><br/>\r\n");
116         writer.append(ticket.getBody()).append("<br/><br/>\r\n");
117 
118         if(ticket.getNumberOfAttachments() > 0)
119         {
120             writer.append("Attachments: ");
121             int i = 0;
122             for(Attachment attachment : ticket.getAttachments())
123             {
124                 if(i++ > 0)
125                     writer.append(", ");
126                 writer.append("<a href=\"tickets?action=download&ticketId=")
127                         .append(idString).append("&attachment=")
128                         .append(attachment.getName()).append("\">")
129                         .append(attachment.getName()).append("</a>");
130             }
131             writer.append("<br/><br/>\r\n");
132         }
133 
134         writer.append("<a href=\"tickets\">Return to list tickets</a>\r\n");
135 
136         this.writeFooter(writer);
137     }
138 
139     private Ticket getTicket(String id, HttpServletResponse response) throws IOException {
140         //id.len == ''  一般合法性检查  有没有
141         if (id == null || id.length()==0){
142             response.sendRedirect("tickets");
143             return null;
144         }
145         try {
146             Ticket ticket = this.ticketDatabase.get(Integer.parseInt(id));
147             if (ticket == null) {
148                 response.sendRedirect("tickets");
149                 return null;
150             }
151             return ticket;
152         }catch (Exception e){
153             response.sendRedirect("tickets");
154             return null;
155         }
156     }
157 
158     private void showTicketForm(HttpServletResponse resp) throws IOException {
159         PrintWriter writer = this.writeHeader(resp);
160         writer.append("<h2>Create a Ticket</h2>\r\n");
161         writer.append("<form method=\"POST\" action=\"tickets\" ")
162                 .append("enctype=\"multipart/form-data\">\r\n");//编码类型multipart/form-data
163         writer.append("<input type=\"hidden\" name=\"action\" ")//隐藏域提交 action value = create
164                 .append("value=\"create\"/>\r\n");
165         writer.append("Your Name<br/>\r\n");
166         writer.append("<input type=\"text\" name=\"customerName\"/><br/><br/>\r\n");
167         writer.append("Subject<br/>\r\n");
168         writer.append("<input type=\"text\" name=\"subject\"/><br/><br/>\r\n");
169         writer.append("Body<br/>\r\n");
170         writer.append("<textarea name=\"body\" rows=\"5\" cols=\"30\">")
171                 .append("</textarea><br/><br/>\r\n");
172         writer.append("<b>Attachments</b><br/>\r\n");
173         writer.append("<input type=\"file\" name=\"file1\"/><br/><br/>\r\n");
174         writer.append("<input type=\"submit\" value=\"Submit\"/>\r\n");
175         writer.append("</form>\r\n");
176 
177         this.writeFooter(writer);
178     }
179 
180 
181     private void downloadAttachment(HttpServletRequest request, HttpServletResponse response) throws IOException {
182        //下载某一个attachment
183         String idString = request.getParameter("ticketId");
184         Ticket ticket = this.getTicket(idString, response);
185         if(ticket == null)
186             return;
187 
188         String name = request.getParameter("attachment");
189         if(name == null)
190         {
191             response.sendRedirect("tickets?action=view&ticketId=" + idString);
192             return;
193         }
194 
195         Attachment attachment = ticket.getAttachment(name);
196         if(attachment == null)
197         {
198             response.sendRedirect("tickets?action=view&ticketId=" + idString);
199             return;
200         }
201         //header 内容位置   文件名
202         response.setHeader("Content-Disposition",
203                 "attachment; filename=" + attachment.getName());
204 
205         response.setContentType("application/octet-stream");
206         //
207         ServletOutputStream stream = response.getOutputStream();
208         stream.write(attachment.getContents());
209     }
210 
211 
212     private void createTicket(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
213         Ticket ticket = new Ticket();
214         ticket.setCustomerName(req.getParameter("customerName"));
215         ticket.setSubject(req.getParameter("subject"));
216         ticket.setBody(req.getParameter("body"));
217 
218         Part filePart = req.getPart("file1");
219         if (filePart!=null){
220             Attachment attachment = this.processAttachment(filePart);
221             if (attachment!=null)
222                 ticket.addAttachment(attachment);
223         }
224         int id;
225         synchronized (this){
226             id = this.TICKET_ID_SEQUENCE++;
227             this.ticketDatabase.put(id,ticket);
228         }
229         resp.sendRedirect("tickets?action=view&ticketId="+id);
230     }
231 
232     private Attachment processAttachment(Part filePart) throws IOException {
233         InputStream inputStream = filePart.getInputStream();//用户输入流
234         ByteArrayOutputStream outputStream = new ByteArrayOutputStream();//写入attachment做准备
235 
236         int read;
237         final byte[] bytes  = new byte[1024];//buffer
238         while((read=inputStream.read(bytes))!=-1){//有多少
239             outputStream.write(bytes,0,read);//写多少
240         }
241 
242         Attachment attachment = new Attachment();
243         attachment.setName(filePart.getSubmittedFileName());
244         attachment.setContents(outputStream.toByteArray());
245 
246         return attachment;
247     }
248 
249     private PrintWriter writeHeader(HttpServletResponse response)
250             throws IOException
251     {
252         response.setContentType("text/html");
253         response.setCharacterEncoding("UTF-8");
254 
255         PrintWriter writer = response.getWriter();
256         writer.append("<!DOCTYPE html>\r\n")
257                 .append("<html>\r\n")
258                 .append("    <head>\r\n")
259                 .append("        <title>Customer Support</title>\r\n")
260                 .append("    </head>\r\n")
261                 .append("    <body>\r\n");
262 
263         return writer;
264     }
265 
266     private void writeFooter(PrintWriter writer)
267     {
268         writer.append("    </body>\r\n").append("</html>\r\n");
269     }
270 
271 }

 

 

【文件下载细节】

1 //header 内容位置   文件名
2 response.setHeader("Content-Disposition",
3         "attachment; filename=" +
4                 new String(attachment.getName().getBytes("UTF-8"),"ISO8859-1"));//浏览器支持的编码是ISO8859-1
5 response.setContentType("application/octet-stream");
6 //流
7 ServletOutputStream stream = response.getOutputStream();
8 stream.write(attachment.getContents());

 


posted @ 2018-03-20 21:20  chenhui7373  阅读(300)  评论(0)    收藏  举报