码迷,mamicode.com
首页 > 移动开发 > 详细

文件的上传与下载实现(react、express,create-react-app脚手架)

时间:2019-11-15 22:01:03      阅读:112      评论:0      收藏:0      [点我收藏+]

标签:信息处理   match   license   ade   说明   tps   后端   hat   multi   

项目结构为前后端分离,中间布了一层node。

文件上传

要求:将文件信息等发送到后台。

html代码

 <input type="file" name="file">

客户端上传文件时的信息处理

可以使用FormData来异步上传一个二进制文件。上传文件时,

  1. 使用form表单上传的,则需要设置表单的 enctype 等于 multipart/form-data,因为该值默认值为application/x-www-form-urlencoded.
  2. 使用axios库上传,需设置Content-Type为multipart/form-data
  3. 使用fetch上传,无需设置Content-Type
const file = document.querySelector(‘[type=file]‘);
const formData = new FormData();
formData.append("file", file.files[0]);
formData.append("userName", "admin");
axios
  .post("/api/list/upload", formData, {
    headers: {
      "Content-Type": "multipart/form-data"
    }
  })
  .then(() => {
    console.log("上传成功");
  });

成功发送数据的样子

技术图片

技术图片

FormData若需传输数组之类的,根据后台所使用的语言和框架选择,例如后台用的是PHP,可以这样写:

fileList.forEach((file) => {
   formData.append(‘files[]‘, file);
});

文件下载

html代码

 <a href="/download/templete" download>模板下载</a>

node端处理

因为项目中使用了express,所以可以直接通过res.download方法来下载文件。
在server.js文件里面添加

//下载文件
const path = require("path");
app.use("/download/", function(req, res) {
  const filepath = path.join(__dirname, req.url + ".xlsx"); // 文件存储的路径
  res.download(filepath);
});

文件结构为

技术图片

问题

因为是使用create-react-app搭建的,在本地开发环境测试下载文件的情况时,总是无法找到正确路径进行下载。后来在create-react-app说明页面的Proxying API Requests in Development模块找到这样一段话。

This way, when you fetch(‘/api/todos‘) in development, the development server will recognize that it’s not a static asset, and will proxy your request to http://localhost:4000/api/todos as a fallback. The development server will only attempt to send requests without text/html in its Accept header to the proxy.

大概意思就是,在开发时请求fetch(‘/api/todos‘),开发服务器意识到它不是静态资产,所以会将请求进行代理。开发服务器只会将Accept头中没有text / html的请求进行代理。

所以在本地开发环境下测试下载文件时,总是不能找到文件的正确路径进行下载。

解决

方法一

开发测试时直接将href写成完整的请求路径。当然,测试完成后,还是要将“http://20.26.150.69:3001”给删掉的。

<a href="http://20.26.150.69:3001/download/templete" download>模板下载</a>

方法二

根据create-react-app说明页面的Configuring the Proxy Manually

All requests matching this path will be proxies, no exceptions. This includes requests for text/html, which the standard proxy option does not proxy.
意思是匹配此路径的所有请求都将是代理,包括对text / html的请求。
所以,可以将package.json里面的

技术图片

改成类似这种形式,将Accept头中有text / html的请求也纳入代理范围内。

技术图片

参考自:
FormData.append()

文件的上传与下载实现(react、express,create-react-app脚手架)

标签:信息处理   match   license   ade   说明   tps   后端   hat   multi   

原文地址:https://www.cnblogs.com/homehtml/p/11869667.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!