javaweb文件上传
程序员文章站
2022-05-08 17:05:47
...
文件上传
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
response.setContentType("text/html; charset=UTF-8");
boolean isMultipartContent = ServletFileUpload.isMultipartContent(request);
if(isMultipartContent) {
try {
//FileItemFactory factory = new DiskFileItemFactory();
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
//限制条件要设置在解析前面
//设置临时文件大小
factory.setSizeThreshold(10240);
//设置临时文件仓库(路径)
factory.setRepository(new File("E:\\upload\\shortTime"));
//设置单个文件最大限制
upload.setSizeMax(20480);
//解析
List<FileItem> items = upload.parseRequest(request);
//迭代器
Iterator<FileItem> iter = items.iterator();
while(iter.hasNext()){
FileItem item = iter.next();
String fileName = item.getFieldName();
int sid = -1;
String sName = null;
if(item.isFormField()) {
System.out.println(item.isFormField());
if(fileName.equals("sid")) {
sid = Integer.parseInt(item.getString("utf-8"));
}
else if(fileName.equals("sName")) {
sName = item.getString("utf-8");
}
}
else {
try {
String nameString = item.getName();
int index=nameString.lastIndexOf("\\");
if(index!=-1) {
nameString=nameString.substring(index+1);
}
//获取文件尾缀位置
int dg = nameString.lastIndexOf(".");
if(dg!=-1) {
//获取文件尾缀
String ext = nameString.substring(dg+1);
if(!ext.equals("png")||ext.equals("gif")||ext.equals("jpg")) {
System.out.println("图片格式有误,只能是gif.png,jpg");
return;//终止
}
}
//获取项目部署路径+上传文件路径
//String path = request.getSession().getServletContext().getRealPath("/upload");
String path = "E:\\upload";
File file = new File(path,nameString);
item.write(file);
return;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}catch(FileUploadBase.SizeLimitExceededException e) {
e.printStackTrace();
PrintWriter out = response.getWriter();
out.println("文件超出限制,最大为20kb");
}catch (FileUploadException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}