vue+springboot檔案上傳下載(前後端分離)

川師吳奇隆發表於2020-12-11

vue+springboot檔案上傳下載(前後端分離)

前言

本文提供了檔案上傳下載案例,前端效果圖如下:
在這裡插入圖片描述

一、檔案上傳

1.前端部分

	  <!--檔案選擇框,為了美觀設定為隱藏-->
      <input
          class="file"
          type="file"
          ref="myfile"
          @change="handleBeforeUpload"
          style="display: none"
        />
      <!--檔案上傳按鈕-->
      <div class="upload">
        <el-button
          @click="clickUpload"
          type="primary"
          size="mini"
          icon="el-icon-upload2"
          >上傳檔案</el-button
        >
      </div>

2.clickUpload方法(用於觸發input標籤的點選事件)

	clickUpload() {
      this.$refs.myfile.click();
    },

3.handleBeforeUpload方法(用於上傳檔案)

axios掛載為:Vue.prototype.$http = axios

	async handleBeforeUpload() {
      let file = this.$refs.myfile.files[0];
      let formData = new FormData();
      formData.append("multipartFiles", file);
      const { data: res } = await this.$http({
        method: "post",
        url: "http://localhost:9000/doc/uploadDoc",
        data: formData,
        headers: { "Content-Type": "multipart/form-data" },
      });
      if (res.state == 200) {
        this.$message.success("上傳成功!");
      }else{
        if(res.state == 303){
          this.$message.error("請上傳doc或docx檔案!");
        }else{
            this.$message.error("上傳失敗!");
        }
      }
      //防止選擇相同檔案不觸發檔案上傳事件
      this.$refs.myfile.value = null;
    },

4.後端部分

	/**
     * 上傳實施大綱
     * @param multipartFiles
     * @param courseid
     * @return
     * @throws SocketException
     * @throws IOException
     */
    @RequestMapping("/uploadDoc")
    public String uploadDoc(MultipartFile[] multipartFiles) throws SocketException, IOException {
        File fileDir = new File(rootPath);
        if (!fileDir.exists() && !fileDir.isDirectory()) {
            fileDir.mkdirs();
        }
        HashMap<String,Object> result = new HashMap<String,Object>();
        try {
            if (multipartFiles != null && multipartFiles.length > 0) {
                for(int i = 0;i<multipartFiles.length;i++){
                    try {
                        if(multipartFiles[i].getOriginalFilename().split("\\.")[1].equals("doc")||multipartFiles[i].getOriginalFilename().split("\\.")[1].equals("docx")){
                        	//檔案的儲存路徑
                            String storagePath = rootPath+multipartFiles[i].getOriginalFilename().split("\\.")[0]+"."+multipartFiles[i].getOriginalFilename().split("\\.")[1];
                            logger.info("上傳的檔案:" + multipartFiles[i].getName() + "," + multipartFiles[i].getContentType() + "," + multipartFiles[i].getOriginalFilename()
                                    +",儲存的路徑為:" + storagePath);
                            multipartFiles[i].transferTo(new File(storagePath));
                            result.put("state",200);
                        }else{
                            result.put("state",303);
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                         result.put("stete",404);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.put("state",404);
        }
        //前端可以通過狀態碼,判斷檔案是否上傳成功
        return JSON.toJSONString(result);
    }

rootPath設定為:

private  final static String rootPath = "E:/upload/";

二、檔案下載

1.前端部分

      <!--檔案下載-->
      <div class="download" v-if="course.dstate!='未上傳'">
        <el-button size="mini" type="success" icon="el-icon-download" @click="downloadDoc">點選下載</el-button>
      </div>

2.downloadDoc方法(實現檔案下載)

async downloadDoc() {
      let formData = new FormData();
      this.$http({
            method: "post",
            url: "doc/downloadDoc",
            data: formData,
            responseType: 'blob'
        })
        .then((res) => {
          const blob = res.data;
          const reader = new FileReader();
          reader.readAsDataURL(blob);
          reader.onload = (e) => {
            const a = document.createElement("a");
            a.download = this.course.path.split("/")[this.course.path.split("/").length-1];
            a.href = e.target.result;
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
          };
        })
        .catch((err) => {
          console.log(err);
        });
    },

3.後端部分

/**
     * 實施大綱下載
     * @param response
     * @param id
     * @return
     * @throws UnsupportedEncodingException
     */
    @RequestMapping("/downloadDoc")
    public String downloadDoc(HttpServletResponse response ) throws UnsupportedEncodingException {
    	//要下載的檔案路徑
        File file = new File("E:/upload.txt");
        //下載後的檔名
        String fileName = "下載檔案.txt"
        if (file.exists()) {
            // 配置檔案下載
            response.setHeader("content-type", "application/octet-stream");
            response.setContentType("application/octet-stream");
            // 下載檔案能正常顯示中文
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            response.setHeader("Content-Length",""+file.length());
            // 實現檔案下載
            byte[] buffer = new byte[1024];
            FileInputStream fis = null;
            BufferedInputStream bis = null;
            try {
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                OutputStream os = response.getOutputStream();
                int i = bis.read(buffer);
                while (i != -1) {
                    os.write(buffer, 0, i);
                    i = bis.read(buffer);
                }
                logger.info("檔案下載完成!!");
            }
            catch (Exception e) {
                e.printStackTrace();
            }
            finally {
                if (bis != null) {
                    try {
                        bis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return null;
    }

相關文章