egg.js ajax上传文件,egg.js 后端+ jquery前端 跨域 文件上传

jquery前端

contentType: false,

processData: false,

// input file改变事件,这里使用vue的写法

handleFileChange (e) {

let formData = new FormData()

formData.append('files', e.target.files[0])

// console.log(e.target.files)

window.$.ajax({

type: 'POST',

url: 'http://localhost:7001/admin/upload',

data: formData,

// 不要设置Content-Type请求头,

// 自动会动设置成 'multipart/form-data', 不要手动设置

contentType: false,

processData: false, // 告诉jQuery不要去处理发送的数据

timeout: 5000,

success: function(res) {

console.log(res)

},

error: function(err) {

console.log(err)

}

})

}

egg.js 后端

// 处理跨域问题

npm i egg-cors --save

// 处理跨域问题

// puglin.js

'use strict';

/** @type Egg.EggPlugin */

module.exports = {

// had enabled by egg

// static: {

// enable: true,

// }

cors: {

enable: true,

package: 'egg-cors',

}

};

// config.default.js

// 上传文件的配置

// https://github.com/eggjs/egg-multipart

config.multipart = {

// 只允许上传的图片格式

whitelist:['.png','.jpg','.jpeg', '.gif', '.mp3', '.mp4'],

// 文件允许大小

fileSize: '50mb',

}

config.security = {

domainWhiteList: ['http://localhost:8080'],

methodnoallow: {

enable: false,

},

xframe: {

enable: false,

},

csrf: {

enable: false,

headerName: 'x-csrf-token',

ignoreJSON: false,

},

}

// 匹配规则 域名+端口 *则为全匹配

// domainWhiteList如果是多个,origin可以删除,cors插件会设置请求的域名为跨域域名.

config.cors = {

origin: 'http://localhost:8080',

allowMethods: 'GET,HEAD,PUT,POST,DELETE,PATCH',

credentials: true

};

// upload.js

'use strict';

// 返回 { code: '000', data: null, msg: '请求成功'} 这个格式的数据

let tools = require('../utils/tools.js')

//node.js 文件操作对象

const fs = require('fs');

//node.js 路径操作对象

const path = require('path');

const sendToWormhole = require('stream-wormhole');

const Controller = require('egg').Controller;

class UploadController extends Controller {

async upload() {

const ctx = this.ctx;

const parts = ctx.multipart();

let part;

let res = null

let fileUrlArr = []

let tempFileUrl

// console.log(res)

// parts() 返回 promise 对象

while ((part = await parts()) != null) {

// console.log(part)

if (part.length) {

// 这是 busboy 的字段

// console.log('field: ' + part[0]);

// console.log('value: ' + part[1]);

// console.log('valueTruncated: ' + part[2]);

// console.log('fieldnameTruncated: ' + part[3]);

// 应该给每一个文件都取一个name

res = tools.getResp('000100', null, '文件列表参数错误')

} else {

if (!part.filename) {

// 这时是用户没有选择文件就点击了上传(part 是 file stream,但是 part.filename 为空)

// 需要做出处理,例如给出错误提示消息

return;

}

// part 是上传的文件流

// console.log('field: ' + part.fieldname);

// console.log('filename: ' + part.filename);

// console.log('encoding: ' + part.encoding);

// console.log('mime: ' + part.mime);

// 文件处理,上传到云存储等等

let result;

let date = new Date()

let m = date.getMonth() + 1

let pUrl = '/md-editor/public/html-page/images/upload/' + date.getFullYear() + (m > 9 ? m : ('0' + m)) + '/'

pUrl = path.join(path.resolve("."), pUrl + part.filename)

console.log('文件路径:', pUrl)

try {

// result = await ctx.oss.put(pUrl + part.filename, part);

result = fs.createWriteStream(pUrl)

await part.pipe(result)

tempFileUrl = pUrl.split('public')

fileUrlArr.push({

url: tempFileUrl[1]

})

res = tools.getResp('000000', fileUrlArr)

} catch (err) {

// 必须将上传的文件流消费掉,要不然浏览器响应会卡死

await sendToWormhole(part);

console.log(err)

res = tools.getResp('000200', null)

}

// console.log(result);

}

}

console.log('and we are done parsing the form!', res);

ctx.body = res

}

}

module.exports = UploadController;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值