springboot+vue Implementation of File Upload and Download

  • 2021-09-20 19:30:54
  • OfStack

This article example for everyone to share springboot + vue to achieve file upload and download the specific code, for your reference, the specific content is as follows

1. File upload (simple upload based on axios)

Technologies used: axios, springboot, vue;
Implementation idea: Select files through h5: input element tags, obtain the selected file path, new fromdata object, set fromdata parameters, set axios corresponding request header, and finally send post request back-end service through axios. The back-end service receives files through MultipartFile. The specific code is as follows:

Front end code:

1. Create an vue object


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. Implement upload component

Add a change event listener to the input tag and call the up method when a change occurs.


<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(); // Create form Object 
  param.append("file", file); // Pass append Toward form Object to add data 
  console.log(param.get("file")); //FormData Private class object, which cannot be accessed, can be accessed through get Judge whether the value is passed in 
  let config = {
  headers: { "Content-Type": "multipart/form-data" }
  }; // Add a request header 
  this.$http
  .post("http://127.0.0.1:8081/data/up", param, config)
  .then(response => {
   console.log(response.data);
  }).catch(
   error=>{
   alert(" Failure ");
   }
  );
 }
 }
};
</script>

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

</style>

Back-end code:

Upload file code


 @RequestMapping(value = "/up", method = RequestMethod.POST)
 @ResponseBody
 public Result<String> uploade(@RequestParam("file") MultipartFile file) {
  try {
   log.error(" Start uploading! ! ! ");
   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(" Upload successfully! ");
  } catch (IOException e) {
   e.printStackTrace();
  }
  Result<String> stringResult = new Result<String>();
  stringResult.setMsg("sue");
  stringResult.setData("file");
  return stringResult;
 }

2. File downloads

The contents of the file are returned through the response output stream, and the core code sets the name of the downloaded file (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");
  // Add the set size downloaded .xlsx The file will not be reported when it is opened Excel  File-level validation and repair have been completed. Some parts of this workbook may have been repaired or discarded " 
//  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");
}

Related articles: