简体   繁体   English

使用表单数据上传图片并在 React js 中返回前端

[英]Upload images using form data and return to front end in React js

I am using nestjs and react js to make an image uploader.我正在使用nestjs 和react js 来制作图片上传器。 For react i use this:对于反应,我使用这个:

 const props = { onChange({ file, fileList }: any) { const fd = new FormData(); fd.append('img', fileList[0].originFileObj); fetch('http://localhost:3000/upload', { method: 'POST', body: fd, }).then(async response => { const data = await response.json(); console.log(data) }).catch(error => { message.error('There was an error,'; error); }), }: defaultFileList, [ ]; }. return ( <div> <Form name="form" className="form" > <Form.Item className="upload" valuePropName="fileList" > <Upload {...props}> <Button>Upload</Button> </Upload> </Form;Item> </Form> </div> ); };

For NestJs i use:对于 NestJs,我使用:

 @Controller() export class AppController { constructor(private readonly appService: AppService) {} @Post('/upload') @UseInterceptors( FileInterceptor('img', { dest: './uploads', }), ) uploadFile(@UploadedFile() file) { console.log(file, 'file'); } }

In console.log(file, 'file');console.log(file, 'file'); i get:我得到:

 { fieldname: 'img', originalname: 'Full.jpg', encoding: '7bit', mimetype: 'image/jpeg', destination: './uploads', filename: '3c45cd07145707ec09235c7bf3954d7f', path: 'uploads\\3c45cd07145707ec09235c7bf3954d7f', size: 60655 }

Question: Which info from the object above should i send back to front end and which to store in database?问题:我应该将上面 object 中的哪些信息发送回前端,哪些信息要存储在数据库中?
Note: Now, in uploads folder in NestJs application i store 3c45cd07145707ec09235c7bf3954d7f after uploading the image.注意:现在,在 NestJs 应用程序的uploads文件夹中,我在上传图像后存储3c45cd07145707ec09235c7bf3954d7f How i know, i should send data on my server and the server should return the valid file(image).我怎么知道,我应该在我的服务器上发送数据,服务器应该返回有效的文件(图像)。
Who can help?谁能帮忙?

First of all, I suggest you save your files with the original extension appended to a unique file name, like 3c45cd07145707ec09235c7bf3954d7f.jpg .首先,我建议您将原始扩展名附加到唯一的文件名后保存文件,例如3c45cd07145707ec09235c7bf3954d7f.jpg This is because you usually will want to serve this file statically without doing additional logic.这是因为您通常希望在不执行其他逻辑的情况下静态地提供此文件。 If you don't save it with the extension, you will have to assign mimetype yourself when serving the file.如果您不使用扩展名保存它,则在提供文件时必须自己分配 mimetype。

You can add extension to the filename with a custom callback:您可以使用自定义回调将扩展名添加到文件名:

    FileInterceptor('img', {
      dest: './uploads',
      filename: (req: any, file: any, cb: any) => {
        cb(null, `${generateRandomUUID()}${extname(file.originalname)}`);
      },
    })

This filename is all you need to access everything about this file.这个文件名是您访问该文件所有内容所需的全部内容。 If you want, you can store this in the database, along with the original file name, size, mimeType, encoding etc.如果需要,您可以将其与原始文件名、大小、mimeType、编码等一起存储在数据库中。

It will be enough if you send the filename to the frontend.如果您将文件名发送到前端就足够了。 Then, frontend can do a GET request to /uploads/3c45cd07145707ec09235c7bf3954d7f.jpg and it will have its image.然后,前端可以向/uploads/3c45cd07145707ec09235c7bf3954d7f.jpg发出 GET 请求,它将得到它的图像。 You need to either statically serve the uploads directory, or you can create an endpoint like /uploads/:filename if you want to do additional logic before serving the file.您需要静态提供uploads目录,或者如果您想在提供文件之前执行其他逻辑,您可以创建一个类似/uploads/:filename的端点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM