项目要用到文件上传,很久没写了,记录一下
前端代码,一个写在表格中的文件上传按钮
<div class="attachFile flex">
<div>
<p><input type="file" id="uploadFile"
style="display: initial;border: 0;
background: #005394;
border-radius: 5px;
color: #fff;
padding: 5px;
width: 200px;" @change="fileUpload"></input>
</p>
</div>
用的是vue axios 发送上传请求
fileUpload(e) {
var filrarr = document.getElementById("uploadFile").files;
var formdata = new FormData();//创建一个表单
for(var i = 0; i < filrarr.length; i++){
formdata.append("file", filrarr[i]);
}
axios({
method: 'post',
url: '/console/upload/uploader',
data: formdata,
withCredentials: true,
}).then((res) => {
console.log(res);
// this.status =res.data.status;
console.log("文件上传成功")
})
},
后端springboot
/**
* 新增---->返回数据加上文件类型
* @param file
* @param request
* @param response
* @return
*/
@RequestMapping(value = "/uploader", method = RequestMethod.POST)
@ResponseBody
public ModelMap postUploader(@RequestParam MultipartFile file, HttpServletRequest request, HttpServletResponse response){
if (!file.isEmpty()) {
if(StringUtils.isEmpty(upConfig.getHardDisk()) && "local".equals(upConfig.getUpType())){
return ReturnUtil.error("请配置上传目录");
}
String diskPath = upConfig.getHardDisk();
//扩展名格式
String extName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
//验证文件类型
if(!fileService.checkExt(extName)){
return ReturnUtil.error("上传文件格式不支持");
}
//根据文件类型获取上传目录
String uploadPath = fileService.getUploadPath(extName);
uploadPath = uploadPath.replace(File.separator,"/");
if(StringUtils.isEmpty(uploadPath)){
return ReturnUtil.error("上传文件路径错误");
}
String fileName = this.nextId()+extName;
String retPath = "";
if("local".equals(upConfig.getUpType()) && StringUtils.isNotEmpty(upConfig.getUpType())){
retPath= fileService.fileSave(file, diskPath, uploadPath, fileName);
}
if("null".equals(retPath)){
return ReturnUtil.error("上传文件异常");
}
Map<String, String> upMap = fileService.getReturnMap(retPath, fileName);
//新增
//----获取文件类型
try {
String fileType = fileService.getFileType(extName);
upMap.put("fileType", fileType);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return ReturnUtil.error("上传文件不规范,");
}
return ReturnUtil.success("上传成功",upMap);
} else {
return ReturnUtil.error("上传文件为空,");
}
}
这样就能正常上传了
,返回的是图片上传后的名称和路径