使用springmvc的transferTo方法上传文件

前端:

<input type="file" id="file" name="file" accept="image/*" v-on:change="fileUpload()" multiple="multiple" />

向后端传送交互需要用 ajaxFileUpload.js


ajaxFileUpload.js的下载链接:

链接:https://pan.baidu.com/s/1tydVp5R7zAs772zU8-ODyA 
提取码:ql4w 

示例:

$.ajaxFileUpload({
type:'POST',
url:'/fileUpload',
fileElementId:['file'],
data : {
"fileType":"image",//上传文件类型
"purpose":"headImg" //用途
},
// dataType: 'text', //服务器返回的数据类型。可以为xml,script,json,html。如果不填写,jQuery会自动判断
secureuri: true, //是否启用安全提交,默认为false。
async : true, //是否是异步
// 告诉jQuery不要去处理发送的数据
processData : false,
contentType : "application/x-www-form-urlencoded; charset=UTF-8",
// 告诉jQuery不要去设置Content-Type请求头
contentType : false,
success:function(result){


},
error:function(data){

}
});

后端:
public Ret fileUpload(@NonNull@RequestParam("file") MultipartFile file, @RequestParam("fileType") String fileType, @RequestParam("purpose") String purpose, HttpServletRequest request) {
if(file == null){
return RetMethod.failure("上传失败,文件不能为空");
}
//返回的访问路径(相对路径)
String returnPath;
//登陆者
ShiroUser user = ShiroKit.getUser();

//用户登录名 用以区分
String loginName=user.getAccount();


//如果fileType为空,则默认为common
if(StringUtils.isEmpty(fileType)){
fileType = "common";
}
//如果purpose为空,则默认为public
if(StringUtils.isEmpty(fileType)){
purpose = "public";
}

//获取原文件的文件名
String oldName=file.getOriginalFilename();

//原文件的类型
String type=oldName.substring(oldName.indexOf(".")); // 格式为.jpg 或 .png 或 ......

//将文件名修改为时间戳,避免原文件出现文件名过长情况
String filename = "/FILE"+new Date().getTime()+type;

// 如果目录不存在则创建
File tempFile=new File(path+baseUrl+"/"+loginName+"/"+fileType+"/"+purpose+"/"+filename);

try{
if (!tempFile.getParentFile().exists()){
tempFile.getParentFile().mkdirs();//创建父级文件路径
tempFile.createNewFile();//创建文件
}
//通过CommonsMultipartFile的方法直接写文件(注意这个时候)
file.transferTo(tempFile);

}catch (IOException e){
return RetMethod.failure("上传失败,失败原因:"+e.getCause());
}
//返回给前台
returnPath=request.getContextPath()+baseUrl+"/"+loginName+"/"+fileType+"/"+purpose+"/"+filename;

return RetMethod.success("上传成功!",returnPath);
}
 
posted @ 2019-07-12 19:15  BrandenFelix  阅读(9147)  评论(0编辑  收藏  举报