上传
前端
<el-upload ref="upload" class="upload-demo" drag :headers="{token:$store.getters.getToken}"
:action="uploadFileUrl" multiple
:on-preview="handlePreview"
:on-remove="handleRemove"
:on-exceed="handleExceed"
:on-success="handleAvatarSuccess"
:before-remove="beforeRemove"
:on-error="uploadError"
:before-upload="beforeUpload"
:limit=20
:file-list="resourcesList"
accept=".doc,.docx,.ppt,.pptx,.txt,.pdf,.xls,.xlsx,.jpg,.png,.gif,.bmp,.mp3,.ape,.ogg,.wav,.mov,.rmvb,.mp4,.mkv,.flv,.wmv,.avi,.mpg">
<i class="el-icon-upload"></i>
<div class="el-upload__text">将文件拖到此处,或<em>点击上传</em></div>
<div class="el-upload__tip" slot="tip">单个文件上传不能超过80MB</div>
</el-upload>
uploadFileUrl: `${home}/upload/uploadFile`,
resourcesList:[],
handleRemove(file, fileList) {
this.resourcesList = [];
for(var i=0;i<fileList.length;i++){
if(fileList[i].response){
this.resourcesList.push(fileList[i].response.data);
}else{
this.resourcesList.push(fileList[i]);
}
}
this.$message.success(`删除成功`);
},
beforeUpload(file) {
var fileSize = file.size / 1024 / 1024;
if (fileSize > 80) {
this.$message.error(`单个文件上传大小不能超过 80MB`);
return false;
}
},
uploadError() {
this.$message.error('文件大小超出范围或出现服务器问题!!');
return false;
},
handlePreview(file) {
},
handleExceed(files, fileList) {
this.$message.warning(`当前限制选择 20 个文件,本次选择了 ${files.length} 个文件,共选择了 ${files.length + fileList.length} 个文件`);
},
beforeRemove(file, fileList) {
return this.$confirm(`确定移除 ${ file.name }?`);
},
handleAvatarSuccess(response, file, fileList) {
this.resourcesList = [];
for(var i=0;i<fileList.length;i++){
if(fileList[i].response){
this.resourcesList.push(fileList[i].response.data);
}else{
this.resourcesList.push(fileList[i]);
}
}
},
后端
配置文件
1.工具类
@Component
public class FileTypeUtil {
public int setResouceType(String suffix) {
//文档后缀数组
String[] docArray = {"doc", "docx", "ppt", "pptx", "txt", "pdf", "xls", "xlsx"};
//图片后缀数组
String[] imgeArray = {"jpg", "png", "gif", "bmp","jpeg"};
//音频后缀数组
String[] voiceArray = {"mp3", "ape", "ogg", "wav"};
//视频后缀数组
String[] videoArray = {"mov", "rmvb", "mp4", "mkv", "flv", "wmv", "avi", "mpg","webm"};
//apk安装包后缀数组
String[] apkArray = {"apk"};
//返回1为文档类型
if (ArrayUtils.contains(docArray, suffix)) {
return 1;
//返回2为图片类型
} else if (ArrayUtils.contains(imgeArray, suffix)) {
return 2;
//返回3为音频类型
} else if (ArrayUtils.contains(voiceArray, suffix)) {
return 3;
//返回4为视频类型
} else if (ArrayUtils.contains(videoArray, suffix)) {
return 4;
//返回5为apk安装包
} else if (ArrayUtils.contains(apkArray, suffix)) {
return 5;
}else{
return 0;
}
}
private String checkFileSize(double len) {
//单位为byte
if (len >= 0 && len < 1024) {
return len + "b";
} else if (len >= 1024) {
len = len / 1024;
if (len >= 1024) {
return String.format("%.2f", len / 1024) + "M";
} else {
return String.format("%.2f", len) + "kb";
}
}
return null;
}
}
@Component
public class FileUtil {
@Value("${file.filePath}")
private String filePath;
@Autowired
private SequenceId sequenceId;
public String uploadFile(MultipartFile file, String suffix){
try {
String fileSuffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
File targetFile = new File(filePath +suffix+DateUtil.format(DateUtil.date(),"yyyy-MM-dd")+"/");
if(!targetFile.exists()){
targetFile.mkdirs();
}
String path = suffix+DateUtil.format(DateUtil.date(),"yyyy-MM-dd")+"/"+ sequenceId.nextId()+fileSuffix;
File dest = new File(filePath +path);
file.transferTo(dest);
return "/"+path;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
2.代码
@Autowired
private FileUtil fileUtil;
@Autowired
private FileTypeUtil fileTypeUtil;
@PostMapping("/uploadFile")
@ApiOperation(value = "创建时间:2018-10-29。说明:上传文件到本地", notes = "返回资源名称和资源的url")
public ResponseJson uploadFile(@ApiParam(value = "上传文件到本地", required = true) MultipartFile file) {
//文件名后缀
String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
int suffixInt = fileTypeUtil.setResouceType(suffix);
if(suffixInt==0){
return new ResponseJson(false,"不支持的文件格式");
}
//不包含文件后缀名
Map<String, String> map = new HashMap<>();
map.put("name", file.getOriginalFilename());
//获取保存文件路径
String url = fileUtil.uploadFile(file, Constant.Upload.UPLOAD_CENTER);//Constant.Upload.UPLOAD_CENTER配置文件下的子文件夹
map.put("url", url);
map.put("fileSize", checkFileSize(file.getSize()));
map.put("type",String.valueOf(suffixInt));
return new ResponseJson(map);
}
下载
前端代码
//下载文件
downloadFile(fileUrl, filename) {
axios({
url: `${home}/upload/downLoadFileLocal`,
method: 'GET',
responseType: "arraybuffer",
params:{
path:fileUrl
}
}).then(res => {
fileDownload(res, filename);
}).catch(error => {
})
},
后端
@Value("${file.filePath}")
private String filePath;
@GetMapping("/downLoadFileLocal")
public HttpServletResponse downLoadFileLocal(String path, HttpServletResponse response) {
try {
// path是指欲下载的文件的路径。
File file = new File(filePath+path);
// 取得文件名。
String filename = file.getName();
// 取得文件的后缀名。
String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();
// 以流的形式下载文件。
InputStream fis = new BufferedInputStream(new FileInputStream(filePath+path));
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
fis.close();
// 清空response
response.reset();
// 设置response的Header
response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));
response.addHeader("Content-Length", "" + file.length());
OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
response.setContentType("application/octet-stream");
toClient.write(buffer);
toClient.flush();
toClient.close();
} catch (IOException ex) {
ex.printStackTrace();
}
return response;
}