springmvc上次文件,ajax请求@RequestMapping("uploadPic") public void uploadPic(@RequestParam MultipartFile myfiles, HttpServletRequest request, HttpServletResponse response){ try { String filena
1、Form表单要加个属性enctype=“multipart/form-data”
<form id=“upload” enctype=“multipart/form-data” method=“post”
<table>
<tr>
<td>头像上传:</td>
<td><input type=file name=“myfiles” id=“doc” onchange=“uploadPic()” />
</td>
<div id=“localImag”>
<img id=“preview” width=200 height=200 style=“diplay:none” />
</div>
</tr>
</table>
</form>
2、用ajax请求
2、用ajax请求
加上这两个字段
contentType: false,
processData: false,
* 头像上次ajax
*/
function uploadPic(){
var formData = new FormData($(“#upload”)[0]);
$.ajax({
url: ‘uploadPic.do’ , /*这是处理文件上传的servlet*/
type: ‘POST’,
data: formData,
async: false,
cache: false,
contentType: false,
processData: false,
success: function (returndata) {
alert(“成功”+returndata);
$(“#preview”).attr(“src”,”http://localhost:8082/upload/”+returndata);
//document.getElementById(“showpic”).src=”<%=basePath%>UploadImage?picture=showpic”;/*这是预览图片用的,自己在文件上传表单外添加*/
},
error: function (returndata) {
alert(returndata);
}
});
}
3、springmvc配置文件
<!– 上传文件的分解器,主要的作用是配置文件上传的一些属性 1.在这个分解器上配置文件的编码方式 2..配置文件最大值 3.配置缓存 –>
<bean id=”multipartResolver” class=”org.springframework.web.multipart.commons.CommonsMultipartResolver”>
<property name=”defaultEncoding”>
<value>UTF-8</value>
</property>
<property name=”maxUploadSize”>
<value>32505856</value>
</property>
<property name=”maxInMemorySize”>
<value>4096</value>
</property>
</bean>
4、springmvc处理请求
Myfiles要跟前端input 的name属性一样
@RequestMapping(“uploadPic”)
public void uploadPic(@RequestParam MultipartFile myfiles, HttpServletRequest request, HttpServletResponse response){
try {
String filename = myfiles.getOriginalFilename();
System.out.println(filename);
User user = (User) request.getSession().getAttribute(“loginUser”);
String newFilename = UUIDUtil.getUUID();
String absolutePath = “F://upload//”;
String extName = filename.substring(filename.lastIndexOf(“.”));
myfiles.transferTo(new File(absolutePath+newFilename+extName)); //存到本地磁盘
response.getWriter().write(newFilename+extName);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}