2019独角兽企业重金招聘Python工程师标准>>>
记录一下文件上传封装Js
代码示例
封装:uploadFile.vue
点击上传
仅支持上传{{this.limitFileNum}}个文件!
调用页面
// html
// 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 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:/";