cloudinary上传文件找不到文件
Posted
技术标签:
【中文标题】cloudinary上传文件找不到文件【英文标题】:cloudinary upload file cannot find file 【发布时间】:2021-08-18 02:43:06 【问题描述】:我想使用 cloudinary 上传文件,但它不起作用。文件字符串参数应该是什么?
@Injectable()
export class CloudinaryService
async uploadImage(
file: Express.Multer.File,
id: string,
): Promise<UploadApiResponse | UploadApiErrorResponse>
return new Promise((resolve, reject) =>
v2.uploader.upload(
file.filename,
public_id: id, folder: 'business', resource_type: 'auto' ,
(error, result) =>
if (error) return reject(error);
resolve(result);
,
);
);
这是文件对象
fieldname: 'DirectorsDetails',
originalname: 'Eddy - Information about directors.xlsx',
encoding: '7bit',
mimetype: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
buffer: <Buffer 50 4b 03 04 14 00 08 08 08 00 14 2a be 52 00 00 00 00 00 00 00 00 00 00 00 00 18 00 00 00 78 6c 2f 64 72 61 77 69 6e 67 73 2f 64 72 61 77 69 6e 67 31 ... 5072 more bytes>,
size: 5122
【问题讨论】:
【参考方案1】:试试这个看看是否有帮助:
调整 multer 以使用内存存储在后期获取缓冲区
// app.module.ts
import MulterModule from '@nestjs/platform-express';
import memoryStorage from 'multer';
@Module(
imports: [
...
MulterModule.register(
storage: memoryStorage(), // use memory storage for having the buffer
),
],
controllers: [AppController],
providers: [AppService],
)
export class AppModule
将缓冲区转为流式传输并引导其上传
import Injectable from '@nestjs/common';
import UploadApiErrorResponse, UploadApiResponse, v2 from 'cloudinary';
import Readable from 'stream';
@Injectable()
export class CloudinaryService
async uploadImage(
file: Express.Multer.File,
): Promise<UploadApiResponse | UploadApiErrorResponse>
return new Promise((resolve, reject) =>
const upload = v2.uploader.upload_stream((error, result) =>
if (error) return reject(error);
resolve(result);
);
Readable.from(file.buffer).pipe(upload); // covert buffer to readable stream and pass to upload
);
如果您想先将其保存到本地目录,您可以这样做,但您需要通过fs.createReadStream
从路径中读取文件以制作它的流并将其上传到 cloudinary。
如果你不能让它工作,我可以上传一个例子到 github 供你交叉检查。
【讨论】:
【参考方案2】:file.filename
仅在您将 multer 文件存储在磁盘上时才会填充。也许file.originalname
就是您要寻找的属性。
【讨论】:
即使上面写着ENOENT: no such file or directory, open filename
【参考方案3】:
尝试使用upload_stream
函数。
import FileUpload from 'graphql-upload';
export class CloudinaryService
async uploadImage(
file: FileUpload,
): Promise<UploadApiResponse | UploadApiErrorResponse>
return new Promise((resolve, reject) =>
const upload = v2.uploader.upload_stream((error, result) =>
if (error) return reject(error);
resolve(result);
);
file.createReadStream().pipe(upload);
);
【讨论】:
上面写着Property 'createReadStream' does not exist on type 'File'
我已经用我使用的类型更新了答案。
还是一样file.createReadStream is not a function
我将文件对象添加到问题中以上是关于cloudinary上传文件找不到文件的主要内容,如果未能解决你的问题,请参考以下文章
为啥我的多文件上传器(使用 Carrierwave 和 Cloudinary)上传文件正常,但没有将所有文件附加到模型/表格?
如何在 Android 中将文件上传到 Cloudinary 时显示进度?