nodejs发送文件到public内,调用oss接口上传文件。
<input type="file" name="" id="photo">
$("#photo").on("change", function () {
let file = $(this)[0].files[0];
let formdata = new FormData();
formdata.append("photo", file);
$.ajax({
type: 'post',
url: '/api/pro/picture',
data: formdata,
contentType: false,
processData: false,
success: function (data) {
}
})
})
const express = require("express");
const router = express.Router();
const fs = require("fs");
const multer = require('multer');
const upload = multer()
const stringRandom = require('string-random');
let OSS = require('ali-oss');
let client = new OSS({
// 仓库地域节点
region: 'oss-cn-shanghai',
//云账号AccessKey有所有API访问权限,建议遵循阿里云安全最佳实践,部署在服务端使用RAM子账号或STS,部署在客户端使用STS。
// oss 中 密钥id
accessKeyId: '***',
// oss 访问权限代码
accessKeySecret: '***',
// 存储仓库名字
bucket: '***',
secure:true // https
cname: true,
endpoint: "xxx.com" 支持自定义域名 必须和cname一起使用
});
router.post(`/picture`, upload.single('photo'), (req, res) => {
// 获取名字
let file_name = req.file.originalname
// 获取后缀名
file_name = file_name.replace(/.+\./, "");
// 生成随机名字
let randomName = stringRandom(16);
// 拼接文件名字
let fileName = randomName + "." + file_name;
// 创建写入流
let ws = fs.createWriteStream('./public/upload/' + fileName);
// 写入buffer数据
ws.write(req.file.buffer);
// 文件写入结束
ws.end(async function () {
// oss仓库地址 要上传文件的地址
let result = await client.put('/images/' + fileName, './public/upload/' + fileName);
if (result.res.status != 200) {
res.json({
code: "400",
msg: "上传失败"
})
} else {
res.json({
data: { pic: result.url },
code: 200,
msg: "上传成功"
})
}
})
})
<el-upload
class="upload-demo"
action=""
multiple
:http-request="upLoadFile"
>
<el-button size="small" type="primary">点击上传</el-button>
</el-upload>
upLoadFile(param){
let fileObject = param.file;
let formData = new FormData();
formData.append("photo", fileObject);
upload(formData)
.then(res=>{
console.log(res);
})
.catch(err=>{
console.log(err);
})
}