记录一下文件上传封装Js
代码示例
封装:uploadFile.vue
<template>
<el-upload
v-model="attachment"
ref="upload"
class="upload-demo"
multiple
:limit="limitFileNum"
:action="uploadUrl"
:file-list="fileList"
:before-upload="beforeUpload"
:before-remove="beforeRemove"
:on-exceed="handleExceed"
:on-success="uploadSuccess"
:on-preview="handlePreview"
:on-remove="handleRemove"
>
<el-button size="small" type="primary" v-if="!hideButton">点击上传</el-button>
<div slot="tip" class="el-upload__tip" style="display: inline-block; margin-left: 10px" v-if="!hideButton">
仅支持上传{{this.limitFileNum}}个文件!
</div>
</el-upload>
</template>
<script>
export default {
name: 'uploadFile',
props: {
inputValue: {
default: ''
},
hideButton: {
default: false
}
},
data() {
return {
uploadUrl: process.env.BASE_API + '/api/fileUtils/uploadFile',
attachment: this.inputValue,
fileList: this.attachment,
suffixName: 'DOC,DOCX,XLS,XLSX,PPT,PDF,TXT,JPG,JPEG,PNG,BMP,GIF',
limitFileNum: 5,
limitFileSize: 20
}
},
mounted() {
window.addEventListener('onscroll', this.handleScroll)
},
watch: {
inputValue: {
immediate: true,
handler: function() {
// 去掉字符中末尾的逗号
if (this.inputValue && this.inputValue.length > 0) {
while (this.inputValue[this.inputValue.length - 1] === ',') {
this.inputValue = this.inputValue.substr(0, this.inputValue.length - 1)
}
}
this.attachment = this.inputValue;
this.fileList = [];
if (this.attachment) {
let list = this.inputValue.split(',');
let object;
for (let i = 0; i < list.length; i++) {
object = {};
object.name = list[i].substring(list[i].lastIndexOf('/') + 1);
object.url = list[i];
this.fileList.push(object);
}
}
}
}
},
methods: {
handleRemove(file, fileList) {
// console.log('需要-删除文件', file);
// console.log('需要-删除文件', file.name);
// console.log('需要-删除文件', file.url);
// console.log('删除文件前', this.attachment);
// 多文件上传问题:上传文件后立即删除-文件地址路径位于file.response.data,而不在file.url。
// 如果是回显文件列表再进行删除,则文件地址位于file.url,而不在file.response.data
// 此处采用多重判断条件
if (undefined !== file.response) {
this.attachment = this.attachment.replace(file.response.data, '');
} else {
let a = this.attachment.split(',');
// 过滤掉数据的空值
a = a.filter(item => item);
// 过滤掉要删的值
a = a.filter(item => item !== file.url);
// 字符串用逗号拼接字符串
this.attachment = a.join(',');
// this.attachment = this.attachment.replace(file.url + ',', '');
}
// this.$emit('childByValue', this.attachment);
// console.log('删除文件后', this.attachment);
// console.log(file, fileList);
},
handlePreview(file) {
this.$confirm('您确定要将文件下载?, 是否继续?', '提示', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning'
}).then(() => {
// console.log('file:' + file.url.substring(0, 4))
if (file.url.substring(0, 5) === 'blob:') {
this.$confirm('请保存信息后再下载!', '提示', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning'
})
return false;
} else {
document.location.href = process.env.BASE_API + '/api/photoUpload/imgDownload?filePath=' + file.url + '&fileName=' + file.name;
}
});
},
handleExceed(files, fileList) {
this.$message.warning('当前限制选择' + this.limitFileNum + '个文件,本次选择了' + files.length + '个文件,共选择了' + (files.length + fileList.length) + '个文件');
},
beforeUpload(file) {
const fileName = file.name;
const suffix = fileName.substring(fileName.lastIndexOf('.') + 1).toUpperCase();
const isSuffix = this.suffixName.indexOf(suffix) !== -1;
const isLtM = file.size / 1024 / 1024 < this.limitFileSize;
if (!isSuffix) {
this.$message.error('上传文件类型必须是' + this.suffixName + '格式!');
}
if (!isLtM) {
this.$message.error('上传文件大小不能超过' + this.limitFileSize + 'MB!');
}
return isSuffix && isLtM;
},
beforeRemove(file, fileList) {
// this.form.declarationAttachment = this.form.declarationAttachment.replace(file.url + ',', '');
// console.log('删除文件前', this.form.declarationAttachment);
// return this.$confirm(`确定移除 ${file.name}?`);
},
uploadSuccess(response, file, fileList) {
// console.log('上传文件', response.data);
if (this.attachment === undefined) {
this.attachment = ''
}
// 去掉字符中的逗号
if (response.data && response.data.length > 0) {
while (response.data[response.data.length - 1] === ',') {
response.data = response.data.substr(0, response.data.length - 1)
}
}
if (!this.attachment) {
this.attachment = response.data;
} else {
this.attachment += ',' + response.data;
}
// this.$emit('childByValue', this.attachment);
}
}
}
</script>
调用页面
// html
<el-row>
<el-col :span="12">
<el-form-item label="附件" prop="otherOrgAttachments" label-width="210px">
<uploadFile :inputValue="form.otherOrgAttachments" ref="otherOrgAttachments" :hideButton ="isShowOtherOrgAttachments"></uploadFile>
</el-form-item>
</el-col>
</el-row>
<el-row>
<el-col :span="12">
<el-form-item label="文件依据" prop="workDocBasis">
<uploadFile :inputValue="form.workDocBasis" ref="workDocBasis" :hideButton ="isShowWorkDocBasis"></uploadFile>
</el-form-item>
</el-col>
</el-row>
// js
import uploadFile from '../../components/uploadFile';
components: { uploadFile },
return {
isShowOtherOrgAttachments: false,
isShowWorkDocBasis: false,
}
// 新增和更新数据方法中添加
this.form.otherOrgAttachments = this.$refs.otherOrgAttachments._data.attachment;
this.form.workDocBasis = this.$refs.workDocBasis._data.attachment;
后端接口
文件上传工具类-FileUtils
package com.hz.common.util;
import com.hz.common.context.BaseContextHandler;
import com.hz.common.dto.RespDTO;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.List;
import java.util.Objects;
/**
* 文件上传
* WEN.C
*/
@RestController
@RequestMapping("/fileUtils")
public class FileUtils {
@RequestMapping(value = "/uploadFile",method = RequestMethod.POST)
public Object uploadFile(@RequestParam("file") List<MultipartFile> files, HttpServletRequest request) {
// 无法获取全局变量,当前用户ID
String UPLOAD_FILES_PATH = "uploadFiles/" + DateUtils.getYear() + "/" + DateUtils.getMonth() + "/" + DateUtils.getDay();
// String UPLOAD_FOLDER = request.getSession().getServletContext().getRealPath(UPLOAD_FILES_PATH);
// 虚拟路径存储 GlobalConfig.USERFILES_FOLDER_URL 为:"D:/"
String UPLOAD_FOLDER = GlobalConfig.USERFILES_FOLDER_URL + UPLOAD_FILES_PATH;
UPLOAD_FILES_PATH = "/" + UPLOAD_FILES_PATH + "/";
if (Objects.isNull(files) || files.isEmpty()) {
return RespDTO.onSuc("文件为空,请重新上传");
}
for(MultipartFile file : files){
String originalFilename = file.getOriginalFilename();
String originalFilenamePrefix = originalFilename.substring(0, originalFilename.lastIndexOf(".")) + "_" + System.currentTimeMillis();
String originalFilenameEnd = originalFilename.substring(originalFilename.lastIndexOf("."), originalFilename.length());
String fileName = originalFilenamePrefix + originalFilenameEnd;
int size = (int) file.getSize();
// System.out.println(fileName + "-->" + size);
if(file.isEmpty()){
return "false";
}else{
File dest = new File(UPLOAD_FOLDER + "/" + fileName);
UPLOAD_FILES_PATH += fileName + ",";
if(!dest.getParentFile().exists()){ //判断文件父目录是否存在
dest.getParentFile().mkdirs();
}
try {
file.transferTo(dest);
}catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return RespDTO.onSuc("文件上传异常");
}
}
}
return RespDTO.onSuc(UPLOAD_FILES_PATH);
}
@RequestMapping(value="/downloadFile")
public void fileDownload(String filePath, String fileName, HttpServletResponse response, HttpServletRequest request) throws UnsupportedEncodingException {
// String UPLOAD_FOLDER = request.getSession().getServletContext().getRealPath(UPLOAD_FILES_PATH);
response.setContentType("multipart/form-data");
fileName=URLEncoder.encode( fileName,"utf-8");
response.setHeader("Content-Disposition", "attachment;fileName="+fileName);
ServletOutputStream out;
File file = new File(GlobalConfig.USERFILES_FOLDER_URL + filePath);
if(!file.exists()){
throw new CommonException(ErrorCode.FAIL,"文件不存在");
}
try {
FileInputStream inputStream = new FileInputStream(file);
out = response.getOutputStream();
int b = 0;
byte[] buffer = new byte[512];
while (b != -1){
b = inputStream.read(buffer);
out.write(buffer,0,b);
}
inputStream.close();
out.close();
out.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* JSON字符串 上传文件路径转换
* @param path
* @return
*/
public static String getFilesPathString(String path){
String all = "[";
if(null != path && !"".equals(path)){
String[] p = path.split(",");
for(String s : p){
all += "{name: " + "'" + s.substring(s.lastIndexOf("/") + 1, s.length()) + "',";
all += "url: " + "'" + s + "'}";
}
}
all += "]";
return all;
}
}
虚拟路径-WebMvcConfig
package com.hz.common.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
/**
* 图片绝对地址与虚拟地址映射
*/
@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
//文件磁盘图片url 映射
//配置server虚拟路径,handler为前台访问的目录,locations为files相对应的本地路径
registry.addResourceHandler(GlobalConfig.USERFILES_BASE_URL).addResourceLocations("file:" + GlobalConfig.USERFILES_ABSOLUTE_URL);
}
}
配置文件-GlobalConfig
public static final String USERFILES_BASE_URL = "/uploadFiles/**";
public static final String USERFILES_ABSOLUTE_URL = "D:/uploadFiles/";
public static final String USERFILES_FOLDER_URL = "D:/";