说明
在实现上传文件时,需要限制文件大小,否则上传 大文件 ,会给服务器带来巨大负担
通过 ServletFileUpload类对象实现:
setFileSizeMax();:设置最大上传文件的大小setSizeMax():设置最大请求的大小
实现
关键代码
// 设置最大文件大小,超过会报错
sfu.setFileSizeMax(MAX_FILE_SIZE);
// 设置最大请求值 (包含文件和表单数据)
sfu.setSizeMax(MAX_REQUEST_SIZE);
完整代码
@WebServlet(urlPatterns ="/upload")
public class UploadServlet extends HttpServlet {
// 上传文件存储目录
private static final String UPLOAD_PATH = "upload";
// 上传配置
private static final int MAX_FILE_SIZE = 1024 * 1024 * 5; // 5MB
private static final int MAX_REQUEST_SIZE = 1024 * 1024 * 6; // 6MB
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
boolean isMC=ServletFileUpload.isMultipartContent(req);
if(isMC){
FileItemFactory fif=new DiskFileItemFactory();
ServletFileUpload sfu=new ServletFileUpload(fif);
// 设置最大文件大小,超过会报错
//一般都会设置文件大小,否则上传1G文件,服务器承受不了
sfu.setFileSizeMax(MAX_FILE_SIZE);
// 设置最大请求值 (包含文件和表单数据)
sfu.setSizeMax(MAX_REQUEST_SIZE);
// 构造保存上传文件的路径
String uploadPath = getServletContext().getRealPath("/"+UPLOAD_PATH) ;
File uploadPathFile=new File(uploadPath);
if(!uploadPathFile.exists()){
uploadPathFile.mkdirs();
}
try {
Map<String, List<FileItem>> map=sfu.parseParameterMap(req);
List<FileItem> imgs=map.get("img");
List<FileItem> descrips=map.get("descrip");
if(imgs!=null && !imgs.isEmpty()){
FileItem img=imgs.get(0);
File uploadFile=new File(uploadPathFile, img.getName());
img.write(uploadFile);
}
if(descrips!=null && !descrips.isEmpty()){
String descrip=descrips.get(0).getString("utf-8");
System.out.println(descrip);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
上传超过大小的文件,报错如下:
org.apache.commons.fileupload.FileUploadBase$SizeLimitExceededException: the request was rejected because its size (14452145) exceeds the configured maximum (6291456)