![](/img/trans.png)
[英]How to implement a resume pause functionality for file upload ? I am using node js, gridfs and multer
[英]I am trying to upload file through node js using multer but I am not getting proper file
我正在使用Multer在Node.js中上传文件,但没有得到正确的文件。 我正在尝试上传图像。 我必须将导入的文件上传到S3存储桶中,但是找不到该文件,我不知道我在哪里错。
这是我的节点js代码:
import "@tsed/multipartfiles";
import Path = require("path");
const rootDir = Path.resolve(__dirname);
const aws = require("aws-sdk");
import { Express } from "express";
import { Controller, Post } from "@tsed/common";
type MulterFile = Express.Multer.File;
import { MultipartFile } from "@tsed/multipartfiles";
@controller("/session")
export class TeleconsultSessionController implements interfaces.Controller {
@httpPost("/uploadDocuments")
public async uploadDocument( @MultipartFile() file: MulterFile, req: Request, res: Response) {
try {
aws.config.update({ accessKeyId: "AKIAIYKXXXXXXXXX", secretAccessKey: "iMzE0wfryXXXXXXXXXXXXXXXXXXXX" });
aws.config.update({ region: "us-east-1" });
const s3 = new aws.S3();
s3.upload({
"Bucket": "teleconsult-development",
"Key": "image",
"Body": file
}, function (err: any, data: any) {
if (err) {
console.log("Error uploading data: ", err);
} else {
console.log(data);
}
});
}
catch (err) {
if (err instanceof ValidationException) {
res.status(400);
res.send({ error: err.getMessage() });
} else {
res.status(500);
res.send({ error: err.getMessage() });
}
}
}
作为回应,当我打过邮递员时,我得到的文件值为:
对象{------ WebKitFormBoundaryAo1BhVpGaB8uYmsw \\ r \\ nContent-Disposition:表单数据; 名称:“” image1“;文件名=” 1528114981689_566_28-1-2
使用multer
上载文件将文件首先保留在服务器的上载文件夹中,具体取决于您的multer设置。
如果一个文件被成功上传multer,你也会得到以下数据req.file
。
{
fieldname: 'file',
originalname: 'sample.jpg',
encoding: '7bit',
mimetype: 'image/jpeg',
destination: './uploads/',
filename: 'd1fccf5dc0125937f6fbe7a4dacfc069',
path: 'uploads/d1fccf5dc0125937f6fbe7a4dacfc069',
size: 23904
}
在下面的示例中,我将使用的path
值不是目录。 Multer会更改您的文件名而无需扩展名。
您将需要以fileStream读取该上传文件,然后将其上传到S3。
例如:
let path = req.file;
let fileStream = fs.createReadStream(file.path);
fileStream.on('error', function (err) {
if (err) { throw err; }
});
fileStream.on('open', function () {
s3.upload({
"Bucket": "yourBucketName",
"Key": file.originalname,
"Body": fileStream
}, function (err: any, data: any) {
if (err) {
console.log("Error uploading data: ", err);
} else {
console.log(data);
}
});
});
希望这对您有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.