溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

在vue項目中使用springboot框架如何實現(xiàn)一個文件上傳下載功能

發(fā)布時間:2020-11-18 14:22:49 來源:億速云 閱讀:363 作者:Leah 欄目:開發(fā)技術(shù)

本篇文章為大家展示了在vue項目中使用springboot框架如何實現(xiàn)一個文件上傳下載功能,內(nèi)容簡明扼要并且容易理解,絕對能使你眼前一亮,通過這篇文章的詳細介紹希望你能有所收獲。

一、文件上傳(基于axios的簡單上傳)

所使用的技術(shù):axios、springboot、vue;
實現(xiàn)思路:通過h6 :input元素標簽進行選擇文件,獲取所選選擇的文件路徑,new fromdata對象,設置fromdata的參數(shù),設置axios對應的請求頭,最后通過axios發(fā)送post請求后端服務。后端服務同過MultipartFile進行文件接收。具體代碼如下:

前端代碼:

1、創(chuàng)建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、實現(xiàn)上傳組件

在input標簽中添加改變事件監(jiān)聽,當發(fā)生改變時調(diào)用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(); //創(chuàng)建form對象
  param.append("file", file); //通過append向form對象添加數(shù)據(jù)
  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輸出流返回文件內(nèi)容,核心代碼設置下載文件的名字(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, 0, 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");
}

上述內(nèi)容就是在vue項目中使用springboot框架如何實現(xiàn)一個文件上傳下載功能,你們學到知識或技能了嗎?如果還想學到更多技能或者豐富自己的知識儲備,歡迎關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI