Java EE之通过表单上传文件

public class Ticket
{
private String customerName; private String subject; private String body; private Map<String, Attachment> attachments = new LinkedHashMap<>(); //...
}
public class Attachment
{
private String name; private byte[] contents; //...
}
@WebServlet(
name = "ticketServlet",
urlPatterns = {"/tickets"},
loadOnStartup = 1
)
@MultipartConfig(
fileSizeThreshold = 5_242_880, //5MB
maxFileSize = 20_971_520L, //20MB
maxRequestSize = 41_943_040L //40MB
)
//@MultipartConfig的location告诉浏览器应该在哪里存储临时文件(这里未使用,让应用服务器使用它的默认临时目录即可)
//fileSizeThreshold将告诉Web容器文件必须达到多大才能写入到临时目录中(在本例中,小于5MB的上传文件将保存在内存中。)
//在本例中,maxFileSize设置将禁止上传大小超过20MB的文件。
//在本例中,maxRequestSize设置禁止大小超过40MB的请求。
public class TicketServlet extends HttpServlet
{
//...
}
public class TicketServlet extends HttpServlet
{
//... //downloadAttachment方法用于处理客户端浏览器的下载请求。
private void downloadAttachment(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
//... //响应中设置的头Content-Disposition,将强制浏览器询问客户是
//保存还是下载文件,而不是在浏览器中在线打开该文件。
response.setHeader("Content-Disposition",
"attachment; filename=" + attachment.getName());
response.setContentType("application/octet-stream"); //使用ServletOutputStream将文件内容输出到响应中(对大文件处理存在内存问题)
ServletOutputStream stream = response.getOutputStream();
stream.write(attachment.getContents());
} //...
}
public class TicketServlet extends HttpServlet
{
//... private void createTicket(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
Ticket ticket = new Ticket();
ticket.setCustomerName(request.getParameter("customerName"));
ticket.setSubject(request.getParameter("subject"));
ticket.setBody(request.getParameter("body")); Part filePart = request.getPart("file1");
if(filePart != null && filePart.getSize() > 0)
{
Attachment attachment = this.processAttachment(filePart);
if(attachment != null)
ticket.addAttachment(attachment);
} int id;
synchronized(this)
{
id = this.TICKET_ID_SEQUENCE++;
this.ticketDatabase.put(id, ticket);
} response.sendRedirect("tickets?action=view&ticketId=" + id);
} private Attachment processAttachment(Part filePart)
throws IOException
{
//从multipart请求中获得InputStream,并将它复制到Attachment对象中。
InputStream inputStream = filePart.getInputStream();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); int read;
final byte[] bytes = new byte[1024]; while((read = inputStream.read(bytes)) != -1)
{
outputStream.write(bytes, 0, read);
} Attachment attachment = new Attachment();
attachment.setName(filePart.getSubmittedFileName());
attachment.setContents(outputStream.toByteArray()); return attachment;
} //...
}

文章的源码链接:https://pan.baidu.com/s/1ZnkwhlZo6_ihutdbgA7FvQ 密码:q33p

其他关于文件上传的源码链接:https://pan.baidu.com/s/1PW-sdelXD6i3S3deFmVi0g 密码:v7hd

《Java Web高级编程》示例代码的下载地址:http://www.wrox.com/go/projavaforwebapps

参考:《Java Web高级编程》第3章 第6节

上一篇:Android 利用an框架快速实现网络请求(含下载上传文件)


下一篇:Chrome 插件编写日记