使用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);
}
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM