public ServletFileUpload getServletFileUpload(DiskFileItemFactory factory) {
ServletFileUpload upload = new ServletFileUpload(factory);
//监听文件上传进度
upload.setProgressListener( new ProgressListener() {
@Override
public void update( long uploaded, long totalSize, int i) {
System.out.println( "已上传:" +(uploaded* 100 )/totalSize+ "%" );
}
});
upload.setHeaderEncoding( "UTF-8" ); //乱码处理
upload.setFileSizeMax( 1024 * 1024 * 10 ); //设置单个文件的最大值10M
upload.setSizeMax( 1024 * 1024 * 100 ); //设置总共能上传文件的最大值100M
return upload;
}
public String uploadParseRequest(ServletFileUpload upload, HttpServletRequest req, String uploadPath) throws FileUploadException, IOException {
String msg = "" ;
//把前端请求解析,封装成一个List对象
List<FileItem> fileItems = upload.parseRequest(req);
for (FileItem fileItem : fileItems) {
if (fileItem.isFormField()) { //判断上传的文件是普通的表单还是带文件的表单
String name = fileItem.getName(); //前端表单控件的name:username
String value = fileItem.getString( "UTF-8" ); //乱码处理
System.out.println(name + ":" + value);
} else { //判断为上传的文件
//==================处理文件=====================
String uploadFileName = fileItem.getName(); //前端表单控件的name
System.out.println( "上传的文件名:" + uploadFileName);
if (uploadFileName.trim().equals( "" ) || uploadFileName == null ) { //可能存在不合法的情况
continue ;
}
String fileName = uploadFileName.substring(uploadFileName.lastIndexOf( "/" ) + 1 ); //文件名
String fileExtName = uploadFileName.substring(uploadFileName.lastIndexOf( "." ) + 1 ); //文件后缀名
System.out.println( "文件名:" + fileName + "--文件后缀:" + fileExtName);
//==================存放地址==================
String uuidPath = UUID.randomUUID().toString();
//文件存储的真实路径
String realPath = uploadPath + "/" + uuidPath;
System.out.println( "文件上传到的位置:" +realPath);
//给每个文件创建一个文件夹
File realPathFile = new File(realPath);
if (!realPathFile.exists()) { //如果文件夹不存在,则创建一个
realPathFile.mkdir();
}
//==================文件传输==================
//获得文件上传的流
InputStream inputStream = fileItem.getInputStream();
//创建一个文件输出流
FileOutputStream fileOutputStream = new FileOutputStream(realPath + "/" + fileName);
//创建一个缓冲区
byte [] buffer = new byte [ 1024 * 1024 ];
//判断读取是否完毕
int len = 0 ;
while ((len = inputStream.read(buffer)) > 0 ) {
fileOutputStream.write(buffer, 0 , len);
}
//关闭流
fileOutputStream.close();
inputStream.close();
msg = "上传成功" ;
fileItem.delete(); //上传成功,清除临时文件
}
}
return msg;
}
|
文件上传的注意事项
1、为保证服务器安全,上传的文件应该放在外界无法直接访问的目录下,例如放在WEB-INF目录下。
2、为了防止文件覆盖的现象,要为上传的文件产生一个唯一的文件名(可以为每一个上传的文件增加一个uuid或时间戳为名的文件夹)
3、限制上传文件的最大值
4、限制上传文件的类型,在收到上传文件时,判断其后缀名是否合法,是否为自己限制的类型
评论(0)