1. 程式人生 > 程式設計 >springboot+vue實現檔案上傳下載

springboot+vue實現檔案上傳下載

本文例項為大家分享了springboot+vue實現檔案上傳下載的具體程式碼,供大家參考,具體內容如下

一、檔案上傳(基於axios的簡單上傳)

所使用的技術:axios、springboot、vue;
實現思路:通過h5 :input元素標籤進行選擇檔案,獲取所選選擇的檔案路徑,new fromdata物件,設定fromdata的引數,設定axios對應的請求頭,最後通過axios傳送post請求後端服務。後端服務同過MultipartFile進行檔案接收。具體程式碼如下:

前端程式碼:

1、建立vue物件

import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import http from 'axios'
Vue.config.productionTip = false;
Vue.prototype.$http=http;
window.vm=new Vue({
 router,store,render: h => h(App)
}).$mount('#app')

2、實現上傳元件

在input標籤中新增改變事件監聽,當發生改變時呼叫up方法。

<template>
 <div class="hello">
 <input
  class="file"
  name="file"
  type="file"
  accept="image/png,image/gif,image/jpeg"
  @change="up" 
 />
 </div>
</template>

<script>

export default {
 name: "HelloWorld",props: {
 msg: String
 },methods: {
 up(e) {
  let file = e.target.files[0];
  alert(file.name);
  console.log(file);
  let param = new FormData(); //建立form物件
  param.append("file",file); //通過append向form物件新增資料
  console.log(param.get("file")); //FormData私有類物件,訪問不到,可以通過get判斷值是否傳進去
  let config = {
  headers: { "Content-Type": "multipart/form-data" }
  }; //新增請求頭
  this.$http
  .post("http://127.0.0.1:8081/data/up",param,config)
  .then(response => {
   console.log(response.data);
  }).catch(
   error=>{
   alert("失敗");
   }
  );
 }
 }
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="less">

</style>

後端程式碼:

上傳檔案程式碼

 @RequestMapping(value = "/up",method = RequestMethod.POST)
 @ResponseBody
 public Result<String> uploade(@RequestParam("file") MultipartFile file) {
  try {
   log.error("開始上傳!!!");
   String originalFilename = file.getOriginalFilename();
   InputStream inputStream = file.getInputStream();
   String path="d:/2020test/";
   File file1 = new File(path + originalFilename);
   if(!file1.getParentFile().exists()){
    file1.getParentFile().mkdirs();
   }
   file.transferTo(file1);
   log.info("上傳成功!");
  } catch (IOException e) {
   e.printStackTrace();
  }
  Result<String> stringResult = new Result<String>();
  stringResult.setMsg("sue");
  stringResult.setData("file");
  return stringResult;
 }

二、檔案下載

通過response輸出流返回檔案內容,核心程式碼設定下載檔案的名字(res.setHeader(“Content-Disposition”,“attachment;filename=” + java.net.URLEncoder.encode(realFileName.trim(),“UTF-8”));)

 @RequestMapping(value = "/get",method = RequestMethod.GET)
 public void downloadFile(HttpServletResponse res) {
  String realFileName="C:/Users/xiongyi/Desktop/12.xls";
  File excelFile = new File(realFileName);
  res.setCharacterEncoding("UTF-8");
  res.setHeader("content-type","application/octet-stream;charset=UTF-8");
  res.setContentType("application/octet-stream;charset=UTF-8");
  //加上設定大小下載下來的.xlsx檔案開啟時才不會報“Excel 已完成檔案級驗證和修復。此工作簿的某些部分可能已被修復或丟棄”
//  res.addHeader("Content-Length",String.valueOf(excelFile.length()));
  try {
   res.setHeader("Content-Disposition","attachment;filename=" + java.net.URLEncoder.encode(realFileName.trim(),"UTF-8"));
  } catch (UnsupportedEncodingException e1) {
   e1.printStackTrace();
  }
  byte[] buff = new byte[1024];
  BufferedInputStream bis = null;
  OutputStream os = null;
  try {
   os = res.getOutputStream();
   bis = new BufferedInputStream(new FileInputStream(new File(realFileName)));
   int i = bis.read(buff);
   while (i != -1) {
    os.write(buff,buff.length);
    os.flush();
    i = bis.read(buff);
   }
  } catch (IOException e) {
   e.printStackTrace();
  } finally {
   if (bis != null) {
    try {
     bis.close();
    } catch (IOException e) {
    }
   }
  }
  Result<String> stringResult = new Result<String>();
  stringResult.setMsg("sue");
  stringResult.setData("nimabi");
}

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。