前端:html
<input type="file" id="file" name="file" accept="image/*" v-on:change="fileUpload()" multiple="multiple" />前端
向後端傳送交互須要用 ajaxFileUpload.jsajax
ajaxFileUpload.js的下載連接:
連接:https://pan.baidu.com/s/1tydVp5R7zAs772zU8-ODyA
提取碼:ql4w
json
示例:後端
$.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);
}