博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Vue-Element-Upload 文件上传复用组件
阅读量:7038 次
发布时间:2019-06-28

本文共 6002 字,大约阅读时间需要 20 分钟。

hot3.png

记录一下文件上传封装Js

代码示例

封装:uploadFile.vue

调用页面

// html
// jsimport 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;/** * 图片绝对地址与虚拟地址映射 */@Configurationpublic 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:/";

 

转载于:https://my.oschina.net/discussjava/blog/2249327

你可能感兴趣的文章
Issue 2:Introduction 方法论
查看>>
[译文]扩展Repeater控件以支持DataPager分页
查看>>
知名网站内部资料:WEB页面内容优化管理与性能技巧
查看>>
20+个可重复使用的jQuery代码片段
查看>>
一致性Hash
查看>>
Mysql jdbc driver源码浅析(一)
查看>>
Super Jumping! Jumping! Jumping!
查看>>
2014 ACM/ICPC Asia Regional Xi'an Online poj5007 Post Robot
查看>>
浅谈P2P
查看>>
[c++]指针的个人理解
查看>>
88. Merge Sorted Array
查看>>
java抽象类和接口区别
查看>>
构建Ruby开发环境(Windows+Eclipse+Aptana Plugin)
查看>>
Miao Xian 隐私政策
查看>>
三维实景下的南极科考站是什么样子?
查看>>
高亮显示用户键盘输入(<kbd>)
查看>>
Linux利用scp命令来进行文件复制
查看>>
【LabVIEW技巧】你可以不懂OOP,却不能不懂封装
查看>>
你是否也忘了刷新视图?
查看>>
完全详解--使用Resource实现多语言的支持
查看>>