微信小程序前台上传图片、后台struts2保存本地的问题。大于2M才能正常保存?
开发一个小程序,需要在小程序上传图片,后台action(struts)保存,前后端代码都写好也调试通过。却遇到个很奇怪的问题。小程序上凡是上传2M(这是经过我反复测试,刚好在这个数值)以上的,后台action可以正常接收并能保存本地。凡是在上传2M以下的,在request里全都获取不到。反复查找了struts里的拦截器,发现正常。前台调用也正常。前后台相关代码如下:
微信小程序:
java代码:
public void upload()throws Exception{
try {
Date date = new Date();
//上传文件
HttpServletRequest request = ServletActionContext.getRequest();
HttpServletResponse response = ServletActionContext.getResponse();
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(4096); // 设置缓冲区大小,这里是4kb
String basePath = ServletActionContext.getRequest().getRealPath("/");//获取根目录
//设置下载目录
String uploadPath = basePath + "/upload";
//设置临时目录
String tempPath = uploadPath +"/temp";
//uploadPath = uploadPath +"/"+ date.getTime();//添加时间目录防止重复
this.initDir(uploadPath, tempPath);
File tempPathFile = new File(tempPath);
factory.setRepository(tempPathFile);// 设置缓冲区目录
ServletFileUpload upload = new ServletFileUpload(factory);
//upload.setSizeMax(34194304); 设置最大文件尺寸,4MB
List items = upload.parseRequest(request);//得到所有的文件
Iterator itr = items.iterator();
String imgUrl;
while(itr.hasNext()){
FileItem fileItem = (FileItem) itr.next();
if(fileItem.isFormField()){
System.out.println("表单参数名:"+fileItem.getFieldName()+",表单参数值:"+fileItem.getString("utf-8"));
}else{
if(fileItem.getName()!=null && !"".equals(fileItem.getName())){
System.out.println("上传文件的大小:"+fileItem.getSize());
System.out.println("上传文件的类型:"+fileItem.getContentType());
System.out.println("上传文件的名称:"+fileItem.getName());
//保存文件
File saveFile = new File(uploadPath,fileItem.getName());
fileItem.write(saveFile);
imgUrl = uploadPath+"/"+fileItem.getName();
System.out.println("上传成功");
}else{
System.out.println("没有上传文件");
}
}
}
Writer out = response.getWriter();
out.write("success");
out.flush();
} catch (Exception e) {
e.printStackTrace();
throw new Exception(e);
}
}
望大家提提意见,看从哪方面着手。