栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

vue和springboot的上传文件和文件夹中的文件以及下载文件

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

vue和springboot的上传文件和文件夹中的文件以及下载文件

(一)、上传文件 1、vue代码

第一个input选择单个和多个文件
第二个input选择文件夹


2、对应的响应方法
data() {
	methods: {
	   //获取文件列表
      getFiles(event){
        var files = event.target.files;
        for (var i=0 ; i{
          if (response.code == 200){
              this.msgSuccess("上传成功!");
          }
        })
      },
	}
}

如果是使用axios调用接口,则是以下代码。



3、后端接口代码
    
    @PostMapping(value = "/uploadF")
    public AjaxResult uploadFile(@RequestParam("files") MultipartFile [] files) throws IOException {
        int result = 0;
        //遍历文件组,取出每个文件对应数据
        for (MultipartFile file:files){
            String fileName = file.getOriginalFilename();
            Long size = file.getSize();
            //D:LearningSoftwareIdeaProjectsRuoYi-Vue-v3.7.0eostest.txt
            String filePath = savaFileByNio((FileInputStream)file.getInputStream(),fileName);
            String saveName= filePath.substring(filePath.lastIndexOf("\")+1,filePath.length());
            String temp = filePath.substring(0,filePath.lastIndexOf("\"));
            String parent = temp.substring(temp.lastIndexOf("\")+1,temp.length());

            //实体类
            EosFileUpload eosFileUpload = new EosFileUpload();
            //filename:test.txt
            // saveName:test.txt
            // size:6
            // filepath:D:LearningSoftwareIdeaProjectsRuoYi-Vue-v3.7.0eostest.txt
            // createUser:admin
            // createTime:Wed Nov 24 14:42:43 CST 2021
            // createUnit:101
            // parent:eos
            eosFileUpload.setFileName(fileName);
            eosFileUpload.setFileNameSaved(saveName);
            eosFileUpload.setFileLength(new BigDecimal(size));
            eosFileUpload.setFilePath(filePath);
            eosFileUpload.setCreateUserId(String.valueOf(getUserId()));
            eosFileUpload.setCreateDate(new Date());
            eosFileUpload.setFilePid(parent);
            result = eosFileUploadService.insertEosFileUpload(eosFileUpload);

        }
        return toAjax(result);
    }

    
    public static String savaFileByNio(FileInputStream fis , String fileName){
        String fileSpace = System.getProperty("user.dir")+ File.separator+"eos";
        String path = fileSpace + File.separator + fileName;

        //判断父文件夹是否存在
        File file = new File(path);
        if (file.getParentFile() != null || !file.getParentFile().isDirectory()){
            file.getParentFile().mkdir();
        }

        // 通过NIO保存文件到本地磁盘
        try {
            FileOutputStream fio = new FileOutputStream(path);
            FileChannel inChannel = fis.getChannel();
            FileChannel outChannel = fio.getChannel();
            inChannel.transferTo(0,inChannel.size(),outChannel);
            inChannel.close();
            outChannel.close();
        }catch (IOException e){
            e.printStackTrace();
        }
        return path;
    }
(二)、下载文件 1、vue代码
下载
2、对应方法
    downloadF(){
      var id = this.ids;
      //需要下载的文件名
      var name = this.names;
      //调用接口
        downLoadFile(id).then(function(response) {
            const blob = response;
            //const blob=new Blob([content]);
            if ('download' in document.createElement('a')) {
                // 非IE下载,创建使用a标签
                const elink = document.createElement('a');
                elink.download = name;
                elink.style.display = 'none';
                elink.href = URL.createObjectURL(blob);
                document.body.appendChild(elink);
                elink.click();
                // 释放URL对象
                URL.revokeObjectURL(elink.href);
                document.body.removeChild(elink);
            } else {
                navigator.msSaveBlob(blob, name)
            }
        }, function(err) {

        })
    }

如果是使用axios调用接口,则是以下代码。

methods: {
	download: function(id, name) {
		this.$axios.get("/file/download/fileId/" + id, {
			responseType: 'blob'
		}).then(function(response) {
			const content = response.data;
			const blob new Blob([content]);
			if ('download' in document.createElement('a')) {
				// 非IE下载
				const elink = document.createElement('a');
				elink.download = name;
				elink.style.display = 'none';
				elink.href = URL.createObjectURL(blob);
				document.body.appendChild(elink);
				elink.click();
				// 释放URL对象
				URL.revokeObjectURL(elink.href);
				document.body.removeChild(elink);
			} else {
				navigator.msSaveBlob(blob, name)
			}
		}, function(err) {

		})
	}
}

3、后端代码
 
    @GetMapping("/download/fileId/{fileId}")
    public ResponseEntity downLoadFile(@PathVariable("fileId")int fileId ,
        HttpServletRequest request)
        throws Exception {
		//根据后台传输的id查询出对应文件信息
        EosFileUpload eosFileUpload = eosFileUploadService.selectEosFileUploadByFileId((long)fileId);
        String fileName = eosFileUpload.getFileName();
        String filePath = eosFileUpload.getFilePath();

        // 解决下载的文件的文件名出现中文乱码
        String userAgent = request.getHeader("User-Agent");
        if (userAgent.contains("MSIE") || userAgent.contains("Trident")) {
            // IE浏览器
            fileName = java.net.URLEncoder.encode(fileName,"UTF-8");
        }else{
            //非IE
            fileName = new String(fileName.getBytes(StandardCharsets.UTF_8),StandardCharsets.ISO_8859_1);
        }

        //下载文件
        byte[] data = Files.readAllBytes(Paths.get(filePath));
        ByteArrayResource resource = new ByteArrayResource(data);

        System.out.println(ResponseEntity.ok()
            .header(HttpHeaders.CONTENT_DISPOSITION,"attachment;filename="+fileName)
            .contentType(MediaType.APPLICATION_OCTET_STREAM)
            .contentLength(data.length)
            .body(resource));
        //<200 OK OK,
        // Byte array resource [resource loaded from byte array],
        // [Content-Disposition:"attachment;filename=test.txt",
        // Content-Type:"application/octet-stream", Content-Length:"6"]>
        return ResponseEntity.ok()
            .header(HttpHeaders.CONTENT_DISPOSITION,"filename="+fileName)
            .contentType(MediaType.APPLICATION_OCTET_STREAM)
            .contentLength(data.length)
            .body(resource);
    }
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/603031.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号