springboot+vue 파일 업로드 다운로드 실현
5003 단어 springbootvue업로드다운로드
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");
}
이상은 본문의 전체 내용입니다. 여러분의 학습에 도움이 되고 저희를 많이 응원해 주십시오.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Kotlin Springboot -- 파트 14 사용 사례 REST로 전환하여 POST로 JSON으로 전환前回 前回 前回 記事 の は は で で で で で で を 使っ 使っ 使っ て て て て て リクエスト を を 受け取り 、 reqeustbody で 、 その リクエスト の ボディ ボディ を を 受け取り 、 関数 内部 ...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.