简体   繁体   中英

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. 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:

 @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'); 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?
Note: Now, in uploads folder in NestJs application i store 3c45cd07145707ec09235c7bf3954d7f after uploading the image. 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 . 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.

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.

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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