js部分用ajaxfileupload.js的方法ajaxfileupload.js是依赖jquery的,所以要引入jquery。
js代码:
function upload(){
var fileName = $(this).val();
$.ajaxFileUpload({
url:rootPath+"/member/upload",
secureuri:false,
fileElementId:'busiAttachment',
dataType:'json',
success:function(data){
}
});
}
其中busiAttchment是<input type="file" id="busiAttchment" name="file" />的id,是必需的。input的name也是必需的,controller里面需要。
然后是controller里面的内容。
@RequestMapping(value = "/upload",method = RequestMethod.POST)
public String upload(HttpServletRequest request,HttpServletResponse response) throws FileUploadException, IOException{
DefaultMultipartHttpServletRequest defaultRequest = (DefaultMultipartHttpServletRequest)request;
MultiValueMap<String, MultipartFile> fileMap = defaultRequest.getMultiFileMap();
List<MultipartFile> fileList = fileMap.get("file");
MultipartFile file = fileList.get(0);
WebApplicationContext webApplicationContext = ContextLoader.getCurrentWebApplicationContext();
ServletContext servletContext = webApplicationContext.getServletContext();
String dirPath = servletContext.getRealPath("/WEB-INF/upload/");
File dir = new File(dirPath);
if(!dir.exists()){
dir.mkdir();
}
String filePath = dirPath+"/"+(new Date().getTime())+file.getOriginalFilename();
File resultFile = inputstreamtofile(file.getInputStream(),filePath);
Map<String,String> result = new HashMap<String, String>();
result.put("filePath", resultFile.getPath());
String jsonResult = JsonUtil.toJsonString(result);
return returnJson(response, jsonResult);
}
其中JsonUtil.toJsonString()和returnJson都是其他jar包里的方法,是公司里其他人提供的。主要就是为了返回json串。pw.wirte(json)这样的方法写。
inputstreamtofile方法:
public File inputstreamtofile(InputStream ins,String fileName) {
File file = new File(fileName);
try {
OutputStream os = new FileOutputStream(file);
int bytesRead = 0;
byte[] buffer = new byte[8192];
while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
os.write(buffer, 0, bytesRead);
}
os.close();
ins.close();
} catch (Exception e) {
e.printStackTrace();
}
return file;
}
在写的过程中遇到的问题:
1、一开始用普通的文件上传的方法,就是在servlet中直接写的那种通用方法:DiskFileItemFactory和ServletFileUpload写的那种。但是在List<?> item = upload.parseRequest(request);之后item为空。网上有解决struts2遇到这个问题的办法,说是request转换为MultipartHttpServletRequest类型的了,只要百度upload.parseRequest(request);返回空结果基本上都是struts2的解决方案。但是在springMVC中,request已经是DefaultMultipartHttpServletRequest类型的了,DefaultMultipartHttpServletRequest里包含上传文件的信息,获取方法看上面的代码。
2、其中有获取realPath的地方,一般在servlet中可以直接用this.servletContext().getRealPath()获取,但是在controller中不行,一开始用的方法是request.getSession().getServletContext().getRealPath("/")。但是报了个共享session不能用此方法。然后就用
ServletContext servletContext = webApplicationContext.getServletContext();
String dirPath = servletContext.getRealPath("/WEB-INF/upload/");
这个来解决了。
这么一个小小的文件上传,没有任何验证,用掉了我几乎一天的时间,看来还是自己各方面知识掌握的不全面。还有很多药学习啊!