網(wǎng)站首頁 編程語言 正文
本文實例為大家分享了react使用axios實現(xiàn)上傳下載的具體代碼,供大家參考,具體內(nèi)容如下
廢話不多說,直接上干貨
上傳文件前臺代碼
上傳也可以使用Antd前臺庫的上傳組件直接上傳,但博主沒有使用,嘗試自己去實現(xiàn)了這個功能
import React, { Component } from 'react'
import Axios from 'axios'
export default class upload extends Component {
? ?
? ? uploadFile = ()=>{
? ? ? ? let file1 = document.querySelector('#input').files[0]
? ? ? ? let formdata = new FormData()
? ? ? ? formdata.append("file", file1) ??
? ? ? ? Axios({
? ? ? ? ? ? url:'/api/importExcel',
? ? ? ? ? ? method: 'post',
? ? ? ? ? ? headers:{'Content-Type':'multipart/form-data'},
? ? ? ? ? ? data:formdata
? ? ? ? }).then(
? ? ? ? ? ? request =>{
? ? ? ? ? ? ? ? console.log(request.data)
? ? ? ? ? ? },
? ? ? ? ? ? error =>{
? ? ? ? ? ? ? ? console.log(error.data)
? ? ? ? ? ? }
? ? ? ? )
? ? }
? ? render() {
? ? ? ? return (
? ? ? ? ? ? <div>
? ? ? ? ? ? ? ? ?<input type="file" id="input" ></input>
? ? ? ? ? ? ? ? ?<button onClick={this.uploadFile}>上傳</button>
? ? ? ? ? ? </div>
? ? ? ? )
? ? }
}
后臺代碼:
```java
@RequestMapping(value = "importExcel", method = RequestMethod.POST)
?? ?private String importExcel(HttpServletRequest request) throws JsonProcessingException {
?? ??? ?boolean result = false;
?? ??? ?MultipartHttpServletRequest params = ((MultipartHttpServletRequest) request);
?? ??? ?List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file");
?? ??? ?MultipartFile file = null;
?? ??? ?BufferedOutputStream stream = null;
?? ??? ?for (int i = 0; i < files.size(); ++i) {
?? ??? ??? ?file = files.get(i);
?? ??? ??? ?if (!file.isEmpty()) {
?? ??? ??? ??? ?try {
?? ??? ??? ??? ??? ?byte[] bytes = file.getBytes();
?? ??? ??? ??? ??? ?stream = new BufferedOutputStream(new FileOutputStream(
?? ??? ??? ??? ??? ??? ??? ?new File(uploadFilePath + File.separatorChar + file.getOriginalFilename())));
?? ??? ??? ??? ??? ?stream.write(bytes);
?? ??? ??? ??? ??? ?stream.flush();
?? ??? ??? ??? ??? ?stream.close();
?? ??? ??? ??? ??? ?result = true;
?? ??? ??? ??? ?} catch (Exception e) {
?? ??? ??? ??? ??? ?System.out.println(e);
?? ??? ??? ??? ?} finally {
?? ??? ??? ??? ??? ?stream = null;
?? ??? ??? ??? ?}
?? ??? ??? ?}
?? ??? ?}
?? ??? ?return "success"
?? ?}
下載文件前臺代碼
下載文件的部分信息,博主放到了返回報文的報文頭中,大家可以通過在前臺打印response就可以看到前臺的response的結(jié)構(gòu),大家也可以放到response報文中的其他地方,博主沒有嘗試
```java
import React, { Component } from 'react'
import Axios from 'axios'
export default class download extends Component {
? ? downLoad = () => {
? ? ? ? Axios(
? ? ? ? ? ? {
? ? ? ? ? ? ? ? url: '/api/exprotFile',
? ? ? ? ? ? ? ? method: 'post',
? ? ? ? ? ? ? ? responseType: 'blob',
? ? ? ? ? ? ? ? data: { 'name': '123' }
? ? ? ? ? ? }
? ? ? ? ).then(
? ? ? ? ? ? response => {
? ? ? ? ? ? ? ? let url = window.URL.createObjectURL(response.data);
? ? ? ? ? ? ? ? let eleLink = document.createElement('a');
? ? ? ? ? ? ? ? eleLink.href = url;
? ? ? ? ? ? ? ? eleLink.download = `${response.headers.filename}`;
? ? ? ? ? ? ? ? document.body.appendChild(eleLink);
? ? ? ? ? ? ? ? eleLink.click();
? ? ? ? ? ? ? ? window.URL.revokeObjectURL(url);
? ? ? ? ? ? },
? ? ? ? ? ? error => {
? ? ? ? ? ? ? ? console.log(error.data)
? ? ? ? ? ? }
? ? ? ? )
? ? }
? ? render() {
? ? ? ? return (
? ? ? ? ? ? <div>
? ? ? ? ? ? ? ? <button onClick={this.downLoad}> 下 載 </button>
? ? ? ? ? ? </div>
? ? ? ? )
? ? }
}
后臺代碼
@RequestMapping(value = "exprotFile", method = RequestMethod.POST)
?? ?@ResponseBody
?? ?private ResponseEntity<FileSystemResource> exportFile(@RequestBody String jsonStr) {
?? ??? ?File file = new File("F:\\uploadFile\\test.txt");
?? ??? ?HttpHeaders headers = new HttpHeaders();
?? ??? ?headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
?? ??? ?headers.add("Content-Disposition");
?? ??? ?headers.add("Pragma", "no-cache");
?? ??? ?headers.add("Expires", "0");
?? ??? ?headers.add("Last-Modified", new Date().toString());
?? ??? ?headers.add("ETag", String.valueOf(System.currentTimeMillis()));
?? ??? ?headers.add("filename", file.getName());
?? ??? ?return ResponseEntity.ok().headers(headers).contentLength(file.length())
?? ??? ??? ??? ?.contentType(MediaType.parseMediaType("application/octet-stream")).body(new FileSystemResource(file));
?? ?}
原文鏈接:https://blog.csdn.net/qwe885167759/article/details/116990113
相關推薦
- 2022-10-14 修改全局 element-ui 元素
- 2023-04-12 Pandas創(chuàng)建DataFrame提示:type?object?'object'?has?no?at
- 2022-10-31 Rust?實現(xiàn)?async/await的詳細代碼_相關技巧
- 2022-03-14 軟件文檔編寫規(guī)范(技術文件編寫規(guī)范)
- 2022-07-17 C#編程報錯System.InvalidOperationException問題及解決_C#教程
- 2022-10-15 Go?Excelize?API源碼閱讀GetPageLayout及SetPageMargins_Go
- 2022-05-08 React的事件處理你了解嗎_React
- 2024-03-10 【Redis】Redis的持久化(備份)
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細win安裝深度學習環(huán)境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權(quán)
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結(jié)
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實現(xiàn)加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發(fā)現(xiàn)-Nac
- Spring Security之基于HttpR
- Redis 底層數(shù)據(jù)結(jié)構(gòu)-簡單動態(tài)字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支