vue+spring完成上传下载

上传

vue
        <el-upload class="upload-demo" :action="fileUpload" :on-preview="download" :on-remove="handleRemove"
            :before-remove="beforeRemove" multiple :limit="30" :on-exceed="handleExceed" :file-list="fileList">
            <el-button size="small" type="primary">点击上传</el-button>
        </el-upload>


		data() {
        return {
            fileList: [],
            fileUpload: base.basePath + base.fileUpload
        };
    }

    basePath: "http://localhost:8801/wxservice",
    fileUpload: "/file/uploadSftp",
后端
    @PostMapping("/upload")
    public R uploadFile(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return R.error("文件为空");
        }
        // 获取文件名
        String fileName = file.getOriginalFilename();// 文件上传后的路径
        log.info("uploadFile fileName:{}", fileName);
        // 文件上传后的路径
        String filePath = null;
        try {
            filePath = new File("").getCanonicalPath() + "/tmp/uploadFile/";
        } catch (IOException e) {
            e.printStackTrace();
        }
        //存储路径
        String tagFilePath = filePath + System.currentTimeMillis() + fileName;
        log.info("tagFilePath:{}", tagFilePath);
        File dest = new File(tagFilePath);
        // 检测是否存在目录
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            log.info("uploadFile file.transferTo:{}");
            file.transferTo(dest);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error(fileName + "上传失败");
        }

        FileDto fileDto = insertFileRecordIntoDB(fileName, tagFilePath);
        return R.ok(fileDto);
    }

下载

vue
download(file) {
            axios({
                url: base.fileDownload + '?id=' + file.id,
                method: 'GET',
                responseType: 'blob' // 表示接收二进制数据
            })
                .then(response => {
                    let blob = new Blob([response.data]);
                    let fileName = file.fileName;
                    if (window.navigator.msSaveOrOpenBlob) {
                        navigator.msSaveBlob(blob, fileName);
                    } else {
                        var link = document.createElement("a");
                        link.href = window.URL.createObjectURL(blob);
                        link.download = fileName;
                        link.click();
                        //释放内存
                        window.URL.revokeObjectURL(link.href);
                    }
                })
                .catch(error => {
                    console.error(error)
                })
        }
后端
   @GetMapping("/download")
    public ResponseEntity<byte[]> downloadFile(String id) throws IOException {
        FileDto fileDto = fileService.getById(id);
        File file = new File(fileDto.getFilePath());
        byte[] data = Files.readAllBytes(file.toPath());
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.setContentDispositionFormData("attachment", file.getName());
        headers.setContentLength(data.length);
        return new ResponseEntity<>(data, headers, HttpStatus.OK);
    }
导包

最后附上接口的导包

import com.example.wxservice.dto.FileDto;
import com.example.wxservice.service.FileService;
import com.example.wxservice.test.ftpfileload.SFTPUtil;
import com.example.wxservice.util.R;
import com.jcraft.jsch.SftpException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.List;

pom

        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.8.10</version>
        </dependency>
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.1</version>
        </dependency>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

不积跬步无以至千里-陕西西安

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值