文件上传
import com.mysql.cj.util.StringUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.ProgressListener;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;
import java.util.UUID;
public class FileUploadPractice extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
if(!ServletFileUpload.isMultipartContent(req)){
return;
}
String uPath = this.getServletContext().getRealPath("/WEB-INF/upload");
File uploadPath = new File(uPath);
if(!uploadPath.exists()){
uploadPath.mkdir();
}
String tmp = this.getServletContext().getRealPath("/WEB-INF/tmp");
File tmpPath = new File(tmp);
System.out.println("ContextPath:"+this.getServletContext().getContextPath());
if(!tmpPath.exists()){
tmpPath.mkdir();
}
DiskFileItemFactory factory = getDiskFileItemFactory(tmpPath);
ServletFileUpload upload = getServletFileUpload(factory);
String msg = "上传错误";
try {
msg = uploadParseRequest(upload, req, uploadPath);
}catch (FileUploadException | IOException e){
e.printStackTrace();
}
req.setAttribute("msg",msg);
req.getRequestDispatcher("fileUploadPractice.jsp").forward(req,resp);
}
private static DiskFileItemFactory getDiskFileItemFactory(File file){
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(1024*1024);
factory.setRepository(file);
return factory;
}
private static ServletFileUpload getServletFileUpload(DiskFileItemFactory factory){
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setProgressListener(new ProgressListener() {
@Override
public void update(long pBytesRead, long pContentLength, int pItems) {
System.out.println("总大小:"+pContentLength+" 已上传:"+pBytesRead);
}
});
upload.setHeaderEncoding("UTF-8");
upload.setFileSizeMax(1024*1024*10);
upload.setSizeMax(1024*1024*10);
return upload;
}
private static String uploadParseRequest(ServletFileUpload upload,HttpServletRequest req,File uploadPath) throws FileUploadException,IOException {
String msg = "";
List<FileItem> fileItems = upload.parseRequest(req);
for(FileItem fileItem:fileItems) {
if (fileItem.isFormField()) {
String name = fileItem.getFieldName();
String value = fileItem.getString("UTF-8");
System.out.println(name+":"+value);
}else {
String uploadFilePath = fileItem.getName();
System.out.println("上传的文件的带路径的文件名:" + uploadFilePath);
if (StringUtils.isNullOrEmpty(uploadFilePath)) {
continue;
}
String fileName = uploadFilePath.substring(uploadFilePath.lastIndexOf("/") + 1);
String fileExtName = uploadFilePath.substring(uploadFilePath.lastIndexOf(".") + 1);
System.out.println("文件信息 [件名:" + fileName + "---文件类型" + fileExtName + "]");
String uuidPath = UUID.randomUUID().toString();
String realPath = uploadPath + "/" + uuidPath;
File realPathDir = new File(realPath);
if (!realPathDir.exists()) {
realPathDir.mkdir();
}
InputStream inputStream = fileItem.getInputStream();
FileOutputStream fos = new FileOutputStream(realPath + "/" + fileName);
byte[] buffer = new byte[1024 * 1024];
int len = 0;
while ((len = inputStream.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
msg = "文件上传成功!";
fileItem.delete();
}
}
return msg;
}
}
文件下载
package org.myweb.servlet;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;
public class FileServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException {
try {
String realPath = this.getServletContext().getRealPath("照片.PNG");
System.out.println("被下载文件的路径:" + realPath);
String fileName = realPath.substring(realPath.lastIndexOf("\\") + 1);
resp.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
FileInputStream in = new FileInputStream(realPath);
int len = 0;
byte[] buffer = new byte[1024];
ServletOutputStream out = resp.getOutputStream();
while ((len = in.read(buffer)) > 0) {
out.write(buffer, 0, len);
}
in.close();
out.close();
}catch(Exception e){
e.printStackTrace();
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}