使用Spring CommonsMultipartResolver 上传文件
@RequestMapping("upload")
@ResponseBody
public OutParam springUpload(HttpServletRequest request)
throws IllegalStateException, IOException {
OutParam outParam = new OutParam();
outParam.setResponseCode("success");
long startTime = System.currentTimeMillis();
// 将当前上下文初始化给 CommonsMutipartResolver (多部分解析器)
ProjectProgramMemo memo = new ProjectProgramMemo();
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
request.getSession().getServletContext());
// 检查form中是否有enctype="multipart/form-data"
if (multipartResolver.isMultipart(request)) {
// 将request变成多部分request
MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
// 获取multiRequest 中所有的文件名
Iterator iter = multiRequest.getFileNames();
while (iter.hasNext()) {
// 一次遍历所有文件
MultipartFile file = multiRequest.getFile(iter.next()
.toString());
if (file != null) {
String webPath = new WebUtils().getWebInfPath() + "upload/";
String path = webPath + file.getOriginalFilename();
// 上传
file.transferTo(new File(path));
// 暂存文件信息
memo.setFileurl(webPath);
memo.setFilename(file.getOriginalFilename());
outParam.setData(memo);
}
}
}
long endTime = System.currentTimeMillis();
System.out.println("方法三的运行时间:" + String.valueOf(endTime - startTime)
+ "ms");
return outParam;
}
--------------------------------------------------------------------------------------------------------------------------------------------------
前端实例
<div class="pull-left ">
<h4>方案说明</h4>
<form id="program_form" action="${ctx }/project/upload" method="post" enctype="multipart/form-data">
<input type="file" name="file" accept="application/msword">
</form>
<button type="button" onclick="uploadFile()">上传</button>
<input type="hidden" id="add_p_fileurl" value=""/>
<input type="hidden" id="add_p_filename" value=""/>
</div>
function uploadFile(){
var form = new FormData(document.getElementById("program_form"));
$.ajax({
url:"${ctx }/project/upload",
type:"post",
data:form,
processData:false,
contentType:false,
success:function(data){
$("#add_p_fileurl").val(data.data.fileurl);
$("#add_p_filename").val(data.data.filename);
},
error:function(e){
alert("错误!!");
}
});
}