springboot+vue 파일 업로드 다운로드 실현

본고의 실례는springboot+vue가 파일 업로드 다운로드를 실현하는 구체적인 코드를 공유하여 참고하도록 하였으며, 구체적인 내용은 다음과 같다.
1. 파일 업로드 (axios 기반의 간단한 업로드)
사용하는 기술:axios,springboot,vue;
실현 사고방식: h5:input 요소 라벨을 통해 파일을 선택하고 선택한 파일 경로를 가져옵니다. newfromdata 대상,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;
 }
2. 파일 다운로드
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, 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");
}
이상은 본문의 전체 내용입니다. 여러분의 학습에 도움이 되고 저희를 많이 응원해 주십시오.

좋은 웹페이지 즐겨찾기