一、前言
本文采用前后端分離式的架構(gòu),其中涉及到文件下載的需求,文件下載在任何系統(tǒng)中都是比較常見的。對于前后端分離架構(gòu)的文件下載與往常的寫法有些許不同(試過直接使用a標(biāo)簽,href填上下載地址,發(fā)現(xiàn)行不通),所以經(jīng)過查找與嘗試,以下文件下載前后端實(shí)現(xiàn)流程供大家參考。
二、準(zhǔn)備
前端:vue + ViewUI
后端:springboot
三、文件下載
1、準(zhǔn)備一個文件下載接口,返回文件流
@GetMapping("/download")
public void downloadFile(HttpServletResponse response) {
? ? // 讀取resource目下文件
? ? String templatePath = "classpath:file/test.txt";
? ? String filename = " test.txt ";
? ? File file = null;
? ? try {
? ? file = ResourceUtils.getFile(templatePath);
? ? } catch (FileNotFoundException e) {
? ? log.warn("文件不存在 {}", filename);
? ? ? ? //?todo,?可以在流中返回“文件不存在“,這樣用戶可以下載到文件,但是內(nèi)容為”文件不存在”
? ? return;
? ? }
? ? if (file.isFile()) {
? ? byte[] fileNameBytes = filename.getBytes(StandardCharsets.UTF_8);
? ? filename = new String(fileNameBytes, 0, fileNameBytes.length, StandardCharsets.ISO_8859_1);
? ? response.reset();
? ? response.setContentType("application/force-download");
? ? response.setCharacterEncoding("utf-8");
? ? response.setContentLength((int) file.length());
? ? response.setHeader("Content-Disposition", "attachment;filename=" + filename);
? ? try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file))) {
? ? byte[] buff = new byte[1024];
? ? OutputStream os = response.getOutputStream();
? ? int i;
? ? while ((i = bis.read(buff)) != -1) {
? ? os.write(buff, 0, i);
? ? os.flush();
? ? }
? ? } catch (IOException e) {
? ? log.error("下載出錯 {},錯誤原因 {}", filename, e.getMessage());
? ? }
? ? } else {
? ? log.warn("文件不存在 {}", filename);
? ? ? ? // todo, 可以在流中返回“文件不存在“,這樣用戶可以下載到文件,但是內(nèi)容為”文件不存在”
? ? }
}
2、前端定義一個button標(biāo)簽,通過點(diǎn)擊按鈕實(shí)現(xiàn)文件下載
<Button type="text" @click.stop.prevent="downloadFile">下載</Button>
3、下載按鈕點(diǎn)擊事件
downloadFile (){
? ? let downloadUrl = "/download"
? ? axios({
? ? ? ? url: downloadUrl,
? ? ? ? method: 'get',
? ? ? ? responseType: 'arraybuffer'
? ? }).then(res => {
? ? ? ? const blob = new Blob([res.data]);
? ? ? ? //創(chuàng)建一個<a></a>標(biāo)簽
? ? ? ? let a = document.createElement("a");
? ? ? ? // 將流文件寫入a標(biāo)簽的href屬性值
? ? ? ? a.href = URL.createObjectURL(blob);
? ? ? ? //設(shè)置文件名
? ? ? ? a.download = "template.py";
? ? ? ? // 隱藏a標(biāo)簽
? ? ? ? a.style.display = "none";
? ? ? ? // 將a標(biāo)簽追加到文檔對象中
? ? ? ? document.body.appendChild(a);
? ? ? ? // 模擬點(diǎn)擊了a標(biāo)簽,會觸發(fā)a標(biāo)簽的href的讀取,瀏覽器就會自動下載了
? ? ? ? a.click();
? ? ? ? //用完就刪除a標(biāo)簽
? ? ? ? a.remove();
? ? })
}
通過以上的做法,就能夠在前后端分離架構(gòu)中實(shí)現(xiàn)文件下載啦!
四、文件上傳
1、后端準(zhǔn)備一個上傳文件接口
@PostMapping("/upload")
public Boolean uploadFile(FileVO fileVO) throws Exception {
String location = "D:\\file";
String user = "001";
? ? // 創(chuàng)建存放文件目錄,一個用戶一個目錄
File dir = Paths.get(location, user).toFile();
if (!dir.isDirectory()) {
boolean mkdirs = dir.mkdirs();
if (!mkdirs) {
log.error("腳本文件保存目錄創(chuàng)建失敗,目錄:{}", dir);
return false;
? ? }
? ? ? ? // 保存腳本文件
? ? ? ? MultipartFile file = fileVO.getFile();
? ? ? ? try {
? ? ? ? file.transferTo(Paths.get(location, user, file.getOriginalFilename()));
? ? ? ? } catch (Exception e) {
? ? ? ? log.error("腳本文件: {} 保存失敗,錯誤原因: {}", file.getOriginalFilename(), e.getMessage());
? ? ? ? return false;
? ? ? ? }
? ? ? ? return true;
? ? }
}
public class ScriptVO {
/**
*文件
*/
private MultipartFile file;
}
2、定義一個上傳標(biāo)簽,通過點(diǎn)擊按鈕實(shí)現(xiàn)文件上傳(如果不是使用ViewUI,那么請使用對應(yīng)前端框架提供的標(biāo)簽)
<div>
? ? <Upload
? ? ? ? :before-upload="handleUpload"
? ? ? ? type="drag">
? ? ? ? <div style="padding: 20px 0">
? ? ? ? <Icon type="ios-cloud-upload" size="52" style="color: #3399ff"></Icon>
? ? ? ? ? ? <p>點(diǎn)擊或拖拽選擇Python腳本文件</p>
? ? ? ? </div>
? ? </Upload>
</div>
<div>
? ? <Button
? ? ? ? type="primary"
? ? ? ? style="margin-left: 8px;"
? ? ? ? @click="submit"
? ? >確認(rèn)</Button>
</div>
3、上傳按鈕點(diǎn)擊事件文章來源:http://www.zghlxwxcb.cn/news/detail-605778.html
handleUpload (file) {
? ? this.uploadFile = file;
? ? return false;
},
submit(){
? ? const formData = new FormData();
? ? formData.append("file", uploadFile);
? ? axios.post('/upload',formData,{
? ? ? ? 'Content-type' : 'multipart/form-data'
? ? }).then(res=>{
? ? ? ? res = res.data
? ? ? ? // 上傳成功后的處理
? ? ? ? if (res == true) {
? ? ? ? // 上傳成功
? ? ? ? }
? ? ? ? else {
? ? ? ? // 上傳失敗
? ? ? ? }
? ? })
}
通過以上的做法,就能夠在前后端分離架構(gòu)中實(shí)現(xiàn)文件上傳啦!文章來源地址http://www.zghlxwxcb.cn/news/detail-605778.html
到了這里,關(guān)于前后端分離架構(gòu)文件上傳與下載(含Vue?+?Spring完整代碼)的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!