一:直接上传文件,放入body里

1.前端代码

  1. <input type="file" onchange="sendFiles(this.files)">
  2. <script>
  3. function sendFiles(files) {
  4. const reader = new FileReader();
  5. const file = files[0];
  6. reader.readAsArrayBuffer(file);
  7. reader.onload = function (e) {
  8. fetch("http://127.0.0.1:3000/" + file.name, {
  9. method: 'post',
  10. body: e.target.result
  11. });
  12. };
  13. }
  14. </script>

2.后端nodejs接受文件并保存

  1. const http = require('http');
  2. const fs = require('fs');
  3. // 这个文件可以 把资料存放到file文件夹下
  4. http.createServer(function (request, response) {
  5. response.setHeader('Access-Control-Allow-Origin', '*');
  6. // 下面的这个意思是放到这个路径下,避免放到根目录
  7. console.log(request.body)
  8. request.pipe(fs.createWriteStream('./file' + request.url, {
  9. // encoding:'binary' // 行
  10. // encoding:'base64' // 行
  11. encoding:'utf8' // 不知道为什么,这里怎么设置都不影响,
  12. }));
  13. response.end(`${request.url} done!`);
  14. }).listen(3000);

二:上传文件支持utf-8以及另存到file文件夹里+带进度条

1.前端代码

  1. // 前端 upload.html
  2. <!DOCTYPE html>
  3. <html>
  4. <head>
  5. <meta charset="utf-8">
  6. <title>上传文件demo</title>
  7. <style media="screen">
  8. .progress{
  9. width: 50%;
  10. height: 5px;
  11. border: 1px solid #ccc;
  12. border-radius: 4px;
  13. margin-top: 10px;
  14. position: relative;
  15. }
  16. .progress>span{
  17. display: inline-block;
  18. position: absolute;
  19. border-radius: 4px;
  20. top: 0;
  21. left: 0;
  22. height: 100%;
  23. width: 0;
  24. background-color: rgb(98, 230, 74);
  25. transition: width 0.3s ease-out;
  26. }
  27. </style>
  28. </head>
  29. <body>
  30. <input id="file" type="file" multiple>
  31. <div class="progress">
  32. <span></span>
  33. </div>
  34. <script type="text/javascript">
  35. var http = function (option) {
  36. // 过滤请求成功后的响应对象
  37. function getBody (xhr) {
  38. var text = xhr.responseText || xhr.response
  39. if (!text) {
  40. return text
  41. }
  42. try {
  43. return JSON.parse(text)
  44. } catch (err) {
  45. return text
  46. }
  47. }
  48. var xhr = new XMLHttpRequest();
  49. // 自定义 beforeSend 函数
  50. if(option.beforeSend instanceof Function) {
  51. if (option.beforeSend(xhr) === false) {
  52. return false
  53. }
  54. }
  55. xhr.onreadystatechange = function () {
  56. if (xhr.status === 200) {
  57. if (xhr.readyState === 4) {
  58. // 成功回调
  59. option.onSuccess(getBody(xhr))
  60. }
  61. }
  62. }
  63. // 请求失败
  64. xhr.onerror = function (err) {
  65. option.onError(err)
  66. }
  67. xhr.open(option.type, option.url, true)
  68. // 当请求为上传文件时回调上传进度
  69. if (xhr.upload) {
  70. xhr.upload.onprogress = function (event) {
  71. if (event.total > 0) {
  72. event.percent = event.loaded / event.total * 100;
  73. }
  74. // 监控上传进度回调
  75. if (option.onProgress instanceof Function) {
  76. option.onProgress(event)
  77. }
  78. }
  79. }
  80. // 自定义头部
  81. const headers = option.headers || {}
  82. for (var item in headers) {
  83. xhr.setRequestHeader(item, headers[item])
  84. }
  85. xhr.send(option.data)
  86. }
  87. // 测试接口
  88. http({
  89. type: 'POST',
  90. url: 'http://127.0.0.1:3000/test',
  91. data: JSON.stringify({
  92. name: 'yolo'
  93. }),
  94. onSuccess: function (data) {
  95. console.log(data)
  96. },
  97. onError: function (err) {
  98. console.log(err)
  99. }
  100. })
  101. document.getElementById('file').onchange = function () {
  102. var fileList = this.files, formData = new FormData();
  103. Array.prototype.forEach.call(fileList, function (file) {
  104. formData.append(file.name, file)
  105. })
  106. // 当上传的数据为 file 类型时,请求的格式类型自动会变为 multipart/form-data, 如果头部格式有特定需求,在我的 http 函数中传入 headers<Object> 即可,大家可自己查看,我这里没有什么特殊处理所以就不传了
  107. http({
  108. type: 'POST',
  109. url: 'http://127.0.0.1:3000/upload',
  110. data: formData,
  111. onProgress: function (event) {
  112. console.log(event.percent)
  113. document.querySelector('.progress span').style.width = event.percent + '%';
  114. },
  115. onSuccess: function (data) {
  116. console.log('上传成功')
  117. },
  118. onError: function (err) {
  119. alert(err)
  120. }
  121. })
  122. }
  123. </script>
  124. </body>
  125. </html>

2.后端代码

  1. // 上传文件支持utf-8以及另存到file文件夹里+带进度条
  2. var express = require('express');
  3. var path = require('path');
  4. var fs = require('fs');
  5. var app = express();
  6. var bodyParser = require('body-parser'); // 过滤请求头部相应格式的body
  7. var multer = require('multer');
  8. var chalk = require('chalk'); // 只是一个 cli 界面字体颜色包而已
  9. var log = console.log.bind(console);
  10. const cors=require('cors');
  11. //跨域请求cors
  12. app.use(cors
  13. (
  14. {
  15. // origin:"*" ,
  16. // origin:"http://localhost:8080" ,
  17. // origin:"http://10.22.12.12:4200" ,
  18. origin:"http://127.0.0.1:5500" ,
  19. credentials: true
  20. }
  21. )
  22. );
  23. app.use(express.static('static'));
  24. // 接受 application/json 格式的过滤器
  25. var jsonParser = bodyParser.json()
  26. // 接受 application/x-www-form-urlencoded 格式的过滤器
  27. var urlencodedParser = bodyParser.urlencoded({ extended: false })
  28. // 接受 text/html 格式的过滤器
  29. var textParser = bodyParser.text()
  30. // 自定义 multer 的 diskStorage 的存储目录与文件名
  31. var storage = multer.diskStorage({
  32. destination: function (req, file, cb) {
  33. cb(null, 'file') // 注意一下这里,这个是设置上传到哪个文件夹的哦~~
  34. },
  35. filename: function (req, file, cb) {
  36. cb(null, file.fieldname)
  37. }
  38. })
  39. var upload = multer({ storage: storage })
  40. // 页面渲染
  41. app.get('/', function (req, res) {
  42. res.sendFile(path.join(__dirname, 'view/upload.html'));
  43. })
  44. app.post('/test', textParser, jsonParser, function (req, res) {
  45. log(req.body);
  46. var httpInfo = http.address();
  47. res.send({
  48. host: httpInfo.address,
  49. port: httpInfo.port
  50. })
  51. })
  52. // 对应前端的上传接口 http://127.0.0.1:3000/upload, upload.any() 过滤时不对文件列表格式做任何特殊处理
  53. app.post('/upload', upload.any(), function (req, res) {
  54. log(req.files)
  55. res.send({message: '上传成功'})
  56. })
  57. // 监控 web 服务
  58. var http = app.listen(3000, '127.0.0.1', function () {
  59. var httpInfo = http.address();
  60. log(`创建服务${chalk.green(httpInfo.address)}:${chalk.yellow(httpInfo.port)}成功`)
  61. })

参考文章:https://blog.csdn.net/yolo0927/article/details/78523020

node.js接收前端上传的文件并保存到其他位置+后端代码支持进度条的更多相关文章

  1. Nodejs学习笔记(八)--- Node.js + Express 实现上传文件功能(felixge/node-formidable)

    目录 前言 formidable简介 创建项目并安装formidable 实现上传功能 运行结果 部分疑惑解析 写在之后 前言 前面讲了一个构建网站的示例,这次在此基础上再说说web的常规功能---- ...

  2. Nodejs学习笔记(八)—Node.js + Express 实现上传文件功能(felixge/node-formidable)

    前言 前面讲了一个构建网站的示例,这次在此基础上再说说web的常规功能----文件上传,示例以一个上传图片的功能为例子 上传功能命名用formidable实现,示例很简单! PS:最近比较忙,距上一次 ...

  3. web api 如何通过接收文件流的方式,接收客户端及前端上传的文件

    服务端接收文件流代码: public async Task<HttpResponseMessage> ReceiveFileByStream() { var stream = HttpCo ...

  4. 基于node.js的websocket上传小功能

    一.node.js 在目录里新建index.js var ws = require("nodejs-websocket"); console.log("开始建立连接... ...

  5. Node.js实现图片上传功能

    node接口实现 const express = require('express') const mysql = require('mysql') const cors = require('cor ...

  6. Node.js之图片上传

    本文用node进行图片上传主要借助formidable插件,具体使用步骤如下: 1.安装formidable插件 npm install formidable -g 2.引入依赖包 const for ...

  7. js截取图片上传(仅原理)----闲的无聊了代码就不共享了!写的难看,不好意思给你们看了(囧)

    就算世界再坑爹,总有一些属性能带你走出绝望(伟大的absolute) 今天吐槽一下!......在我的世界里没有正统UI,所以效果图永远都是那么坑爹! 这里我要感谢有个position:absolut ...

  8. Azure IoT Hub 十分钟入门系列 (4)- 实现从设备上传日志文件/图片到 Azure Storage

    本文主要分享一个案例: 10分钟内通过Device SDK上传文件到IoTHub B站视频:https://www.bilibili.com/video/av90224073/ 本文主要有如下内容: ...

  9. python实现socket上传下载文件-进度条显示

    在python的socket编程中,可以实现上传下载文件,并且在下载的时候,显示进度条,具体的流程如下图所示: 1. 服务器端代码如下: [root@python 519]# cat server.p ...

  10. node之post提交上传

    post文件上传 multer 中间件 在node中 express为了性能考虑采用按需加载的方式,引入各种中间件来完成需求, 平时解析post上传数据时候,是用body-parse.但这个中间件有缺 ...

随机推荐

  1. letcode-学习-数组去重

    数组去重 问题描述: 给你一个 升序排列 的数组 nums ,请你 原地 删除重复出现的元素,使每个元素 只出现一次 ,返回删除后数组的新长度.元素的 相对顺序 应该保持 一致 . 由于在某些语言中不 ...

  2. element-plus 消息提示

    用来显示「成功.警告.消息.错误」类的操作 <template> <el-button :plain="true" @click="open2" ...

  3. Istio Ambient Mesh七层服务治理图文详解

    摘要:本文主要集中剖析Ambient mesh七层服务治理相关内容. 本文分享自华为云社区<Istio Ambient Mesh七层服务治理图文详解>,作者:华为云云原生团队. 由于Amb ...

  4. 基于Spring的发布订阅模式 EventListener

    基于Spring的发布订阅模式 在我们使用spring开发应用时,经常会碰到要去解耦合一些依赖调用,比如我们在做代码的发布流程中,需要去通知相关的测试,开发人员关注发布中的错误信息.而且通知这个操作又 ...

  5. php 程序员进化之路

    1.目标明确 2.消除干扰 3.自我激励 鸟哥 --2018年11月17日php年会

  6. centos7 redis6.2.6安装

    1. 源码包下载并解压 wget http://download.redis.io/releases/redis-6.2.6.tar.gz tar -zxvf redis-6.2.6.tar.gz 2 ...

  7. python贪心算法——以“修理牛棚”题目为例

    [USACO1.3]修理牛棚 Barn Repair 题目描述 在一个月黑风高的暴风雨夜,Farmer John 的牛棚的屋顶.门被吹飞了 好在许多牛正在度假,所以牛棚没有住满. 牛棚一个紧挨着另一个 ...

  8. 【Java EE】Day01 基础加强、Junit单元测试、反射、注解

    〇.总结 1.测试:三个注解.断言判断 2.反射:三个阶段获取字节码对象的三种方式.忽略成员变量权限方法setAccessible(true) 3.注解:内置注解SupressWarning& ...

  9. whistle证书过期或不信任

    1. 安卓设备 , whistle抓包https安装证书后无法访问网络,报证书过期或不信任 2. 查看证书日期是到2030年,没有过期 3. 删除证书 重新安装时候证书选择 "VPN或应用& ...

  10. python安装清华源

    pip install pip -Upip config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple# "pi ...