react + express / koa2 文件上传
2019-07-05 本文已影响0人
七彩霞光_d533
前台代码 react + axios
import React, {Component} from 'react'
import axios from 'axios';
export default class Mycenter extends Component{
constructor(){
super()
this.state = {
}
this.file = null;
}
clickUpload =()=>this.file.click()
handleFileChange =()=>{
let newfile = this.file.files[0];
const formData = new FormData();
formData.append('file', newfile,newfile.name);
const config ={
headers:{
'Content-Type':'application/x-www-form-urlencoded'
}
}
axios.post('http://localhost:8080/upfile/add', formData,config).then( res => {
console.log(res, ":图片上传成功后返回")
}).catch( err => console.log(err))
}
render(){
return (
<div className="profile_box">
<a onClick={this.clickUpload}>选择文件</a>
<input type="file" ref={ file => this.file = file} style={{display:'none'}}/>
<button onClick={this.handleFileChange}>上传</button>
</div>
)
}
}
react + antd( Upload组件 )
import React, {Component} from 'react'
import {Upload, message, Icon } from 'antd'
const Dragger = Upload.Dragger;
export default class Mycenter extends Component{
state = {
}
handleChange = (info)=> {
const status = info.file.status;
if (status !== 'uploading') {
console.log(info.file, info.fileList);
}
if (status === 'done') {
message.success(`${info.file.name} file uploaded successfully.`);
} else if (status === 'error') {
message.error(`${info.file.name} file upload failed.`);
}
}
render(){
const props = {
name: 'file',
action:'http://localhost:8080/upfile/add',
// multiple: true,
showUploadList: false,
onChange: this.handleChange,
};
return (
<div className="profile_box">
<Dragger {...props}>
<p className="ant-upload-drag-icon">
<Icon type="inbox" />
</p>
<p className="ant-upload-text">Click or drag file to this area to upload</p>
<p className="ant-upload-hint">
Support for a single or bulk upload. Strictly prohibit from uploading company data or other
band files
</p>
</Dragger>
</div>
)
}
}
express + multiparty 文件上传
const express= require('express');
const multiparty=require('multiparty')
const fs = require('fs');
const path= require("path");
const uuid=require('uuid')
const app=express();
//读取图片目录
app.use(express.static('public'))
//上传文件目录
app.use('/upload',express.static('upload'))
app.post('/adddata',function (req,res) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Content-Type,Content-Length, Authorization, Accept,X-Requested-With");
res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
const form = new multiparty.Form();
//设置单文件大小限制 2M
form.maxFieldsSize = 2 * 1024 * 1024;
form.uploadDir='upload'
form.parse(req,function (err,flields,files) {
console.log(files, " :files")
if(err){
res.send({ msg: '文件上传失败:' }).end();
}
//拿到扩展名
const extname = path.extname(files.file[0].originalFilename);
//uuid生成 图片名称
const nameID = (uuid.v4()).replace(/\-/g,'');
const oldpath = path.normalize(files.file[0].path);
//新的路径
let newfilename = nameID+extname;
var newpath = './upload/'+newfilename;
//改名
fs.rename(oldpath,newpath,function(err){
if(err){
res.send({ msg: '文件上传失败:' }).end();
}else{
res.send({ msg: '文件上传成功:' }).end();
}
})
})
})
app.listen(8090)
koa+ multer 文件上传
- router / upfile.js
let Router = require('koa-router')
const fileRouter = new Router()
const db = require('../mysql')
const path = require('path')
const uuid = require('uuid')
const fs = require('fs')
const multer=require('koa-multer')
//文件上传
var storage = multer.diskStorage({
//文件保存路径
destination: function (req, file, cb) {
cb(null, 'upload/')
},
//修改文件名称
filename: function (req, file, cb) {
var fileFormat = (file.originalname).split("."); //以点分割成数组,数组的最后一项就是后缀名
cb(null,Date.now() + "." + fileFormat[fileFormat.length - 1]);
}
})
//加载文件配置
var upload = multer({ storage, });
fileRouter.post('/upfile/add',upload.single('file'),async(ctx,next)=>{
let file = ctx.req.file;
// console.log(file,"file")
//拿到扩展名
const extname = path.extname(file.originalname);
//uuid生成图片名称
const nameID = (uuid.v4()).replace(/\-/g,'');
const oldpath = path.normalize(file.path);
//新的路径
let newfilename = nameID + extname;
var newpath = './upload/'+newfilename;
//改名
fs.rename(oldpath,newpath,function(err){
// 改名失败
if(err){
ctx.body = {
code:1,
msg:'err',
data:{}
}
}
})
// 存储到服务器
let ID = uuid.v4().replace(/-/g,'');
const insertfile = `INSERT INTO upfiles (ID,src) VALUES('${ID}','${newfilename}')`
const data = await db.query(insertfile)
let resdata = data.code == 0?{ids:[ID]}:{};
ctx.body = {
code:0,
msg:'ok',
data:resdata,
}
})
module.exports = fileRouter
- server.js 主文件
const koa = require('koa')
const bodyParser = require('koa-bodyparser');
const cors = require('koa2-cors')
const staticFile = require('koa-static')
const path = require('path')
const multer = require('koa-multer')
const file_router = require('./router/upfile')
const server= new koa()
server.use(cors());//解决跨域
server.use(bodyParser()); //接受http请求数据
server.use(staticFile(path.join(__dirname + '/static/'))) // 配置默认访问地址
//文件保存路径
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'upload/')
},
//修改文件名称
filename: function (req, file, cb) {
var fileFormat = (file.originalname).split("."); //以点分割成数组,数组的最后一项就是后缀名
cb(null,Date.now() + "." + fileFormat[fileFormat.length - 1]);
}
})
//加载文件配置
var upload = multer({ storage, });
server
.use(file_router.routes()) // 上传文件
.use(router.allowedMethods());
server.listen(8080)
- koa 常用中间件
koa-router // 路由
koa-static // 静态目录
koa2-cors // 解决跨域
koa-views // 模板引擎
koa-jwt //生成 --- 解密 tocken
koa-session // session 会话存储
koa-logger //日志
koa-compress // 压缩
koa-convert // 版本兼容