1、表单设置
JSP<form action="/uploadservlet" method="post" enctype="multipart/form-data">
2、Servlet文件上传:doPost
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (isMultipart) {
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
try {
List items = upload.parseRequest(request);
Iterator iterator = items.iterator();
while (iterator.hasNext()) {
FileItem item = (FileItem) iterator.next();
if (!item.isFormField()) {
String fileName = item.getName();
String root = getServletContext().getRealPath("/");
File path = new File(root + "/uploads");
if (!path.exists()) {
boolean status = path.mkdirs();
}
File uploadedFile = new File(path + "/" + fileName);
System.out.println(uploadedFile.getAbsolutePath());
item.write(uploadedFile);
}
}
3、Servlet文件下载:
public void doGet(HttpServletRequest request,HttpServletResponse response){
String aFilePath = null; //要下载的文件路径
String aFileName = null; //要下载的文件名
FileInputStream in = null; //输入流
ServletOutputStream out = null; //输出流
try
{
aFilePath = getFilePath(request);
aFileName = getFileName(request);
response.setContentType(getContentType(aFileName) + "; charset=UTF-8");
response.setHeader("Content-disposition", "attachment; filename=" + aFileName);
in = new FileInputStream(aFilePath + aFileName); //读入文件
out = response.getOutputStream();
out.flush();
int aRead = 0;
while((aRead = in.read()) != -1 & in != null)
{
out.write(aRead);
}
out.flush();
}