springmvc 文件上传

1.配置

<!-- 文件上传 -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 上传文件大小限制 -->
<property name="maxUploadSize">
<value>10485760</value>
</property>
<!-- 请求的编码格式, 和 jsp 页面一致 -->
<property name="defaultEncoding">
<value>UTF-8</value>
</property>
</bean>

defaultEncoding="UTF-8" 是请求的编码格式,默认为iso-8859-1
maxUploadSize=10485760" 是上传文件的大小,单位为字节

2.控制层

@RequestMapping(value="/upload_photo",method=RequestMethod.POST)
@ResponseBody
public Map<String, String> upload_photo(MultipartFile photo,HttpServletRequest request){

Map<String, String> ret=new HashMap<String,String>();

//(1)获取文件后缀
String suffix = photo.getOriginalFilename().substring(photo.getOriginalFilename().lastIndexOf(".")+1,photo.getOriginalFilename().length());

if(!"jpg,jpeg,gif,png".toUpperCase().contains(suffix.toUpperCase())){
ret.put("type", "error");
ret.put("msg", "请选择jpg,jpeg,gif,png格式的图片!");
return ret;
}

//(2)文件保存的目录

String savePath = request.getServletContext().getRealPath("/") + "/resources/upload/";
File savePathFile = new File(savePath);
if(!savePathFile.exists()){
//若不存在改目录,则创建目录
savePathFile.mkdir();
}

//(3)创建新的文件名

String filename = new Date().getTime()+"."+suffix;

//(4)转存文件
try {
//将文件保存至指定目录
photo.transferTo(new File(savePath+filename));
}catch (Exception e) {
// TODO Auto-generated catch block
ret.put("type", "error");
ret.put("msg", "保存文件异常!");
e.printStackTrace();
return ret;
}

//(5)将文件路径保存下来返回给前端

ret.put("filepath",request.getServletContext().getContextPath() + "/resources/upload/" + filename );

return ret;

}

3.前端

<tr>
<td width="60" align="right">头像预览:</td>
<td valign="middle">
<img id="preview-photo" style="float:left;" src="/*******/resources/admin/easyui/images/user_photo.jpg" width="100px">
<a style="float:left;margin-top:40px;" href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-upload" onclick="uploadPhoto()" plain="true">上传图片</a>
</td>
</tr>
<tr>
<td width="60" align="right">头像:</td>
<td><input type="text" id="add-photo" name="photo" value="/********/resources/admin/easyui/images/user_photo.jpg" readonly="readonly" class="wu-text " /></td>
</tr>
<tr>

<!-- 进度条 -->
<div id="process-dialog" class="easyui-dialog" data-options="closed:true,iconCls:'icon-upload',title:'正在上传图片'" style="450px; padding:10px;">
<div id="p" class="easyui-progressbar" style="400px;" data-options="text:'正在上传中...'"></div>
</div>
<input type="file" id="photo-file" style="display:none;" onchange="upload()">

js处理:

//上传图片
function start(){
var value = $('#p').progressbar('getValue');
if (value < 100){
value += Math.floor(Math.random() * 10);
$('#p').progressbar('setValue', value);
}else{
$('#p').progressbar('setValue',0)
}
};
function upload(){
if($("#photo-file").val() == '')return;
var formData = new FormData();
formData.append('photo',document.getElementById('photo-file').files[0]);
$("#process-dialog").dialog('open');
var interval = setInterval(start,200);
$.ajax({
url:'upload_photo',
type:'post',
data:formData,
contentType:false,
processData:false,
success:function(data){
clearInterval(interval);
$("#process-dialog").dialog('close');
if(data.type == 'success'){
$("#preview-photo").attr('src',data.filepath);
$("#add-photo").val(data.filepath);
$("#edit-preview-photo").attr('src',data.filepath);
$("#edit-photo").val(data.filepath);
}else{
$.messager.alert("消息提醒",data.msg,"warning");
}
},
error:function(data){
clearInterval(interval);
$("#process-dialog").dialog('close');
$.messager.alert("消息提醒","上传失败!","warning");
}
});
}

function uploadPhoto(){
$("#photo-file").click();//触发photo-file元素的click事件。
}

FormData的主要用途有两个:
1、将form表单元素的name与value进行组合,实现表单数据的序列化,从而减少表单元素的拼接,提高工作效率。
2、异步上传文件
将本地数据(.xlsx、.docx等文件)上传或导入数据库,有时候需要使用FormData 对象。FormData对象,可以把所有表单元素的name与value组成一个queryString,提交到后台。
使用FormData的最大优点就是我们可以异步上传一个二进制文件.
链接:https://www.jianshu.com/p/51188659d778

https://www.jianshu.com/p/9ee4cb347d91

原文地址:https://www.cnblogs.com/cstxx77/p/12691848.html