0
点赞
收藏
分享

微信扫一扫

react上传图片文件到服务器——其他类似——multer修改后缀名后存储——返回静态资源


上传图片文件到服务器

客户端

第一步,获取input对象type为file的对象

  • 通过ref获取对象

//获取第一个File对象
//当上传文件为多个时,通过循坏获取多个File对象
import React, { Component,createRef } from 'react';
fromRef = createRef();



<input type="file" ref={this.fromRef}/>
console.dir(this.state.fromRef.current);
let File = this.state.fromRef.current.files[0];//获取真实文件对象
console.log(File);

第二步、创建formData()对象,插入对象

var fd = new FormData();
fd.append("file",File);
let data = await post("http://10.9.46.247:4000/fdphoto",fd,{
headers:{
"content-type":"multiparty/form-data"
}
})

以下fielname(字符串)必须前端传过来的myformData对象的属性名一致,不然后端接收不到这个文件对象

react上传图片文件到服务器——其他类似——multer修改后缀名后存储——返回静态资源_javascript

服务端

目录结构

react上传图片文件到服务器——其他类似——multer修改后缀名后存储——返回静态资源_服务器_02


部分代码描述:

const multer = require('multer')
// const upload = multer({dest: 'uploads/'})
const storage = multer.diskStorage({
destination: function (req, file,) {
cb(null, 'public/img/')//存储路径
},
filename: function (req, file,) {
var singfileArray = file.originalname.split('.');//扩展后缀
var fileExtension = singfileArray[singfileArray.length - 1];
const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9)
cb(null, file.fieldname + '-' + uniqueSuffix+"." + fileExtension);
console.log(file);
}
})
const upload = multer({
storage
})

合并后缀名写法是这样子的

var singfileArray = file.originalname.split('.');
var fileExtension = singfileArray[singfileArray.length - 1];
const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9)
cb(null, file.fieldname + '-' + uniqueSuffix+"." + fileExtension);
console.log(file);

react上传图片文件到服务器——其他类似——multer修改后缀名后存储——返回静态资源_前端_03


react上传图片文件到服务器——其他类似——multer修改后缀名后存储——返回静态资源_javascript_04


这样就可在vscode中打开了。

设置公共资源目录,可以随意访问

访问图库的资源:

app.use(express.static('./public'))
++++++++
app.post('/fdphoto', upload.single('file'), (req,) => {
res.send({
path: 'http://localhost:4000/img/' + req.file.filename
})
})


举报

相关推荐

0 条评论