反应 axios 上传文件并保存到服务器

时间:2021-07-15 21:24:35

标签: reactjs axios form-data

我正在尝试使用 FormData 上传图像并将其保存到本地主机上的特定文件夹中。我可以看到数据在那里,因为控制台日志向我显示了名称和其他信息。我认为问题出在 axios.post 上,因为控制台告诉我我的本地主机上的上传位置没有找到。只是不知道该怎么办。

这是我的 App.js 文件:

import axios from 'axios';
import React,{Component} from 'react';
 
class App extends Component {
    state = {
 
      // Initially, no file is selected
      selectedFile: null
    };
    
    // On file select (from the pop up)
    onFileChange = event => {
    
      // Update the state
      this.setState({ selectedFile: event.target.files[0] });
    
    };
    
    // On file upload (click the upload button)
    onFileUpload = () => {
    
      // Create an object of formData
      const formData = new FormData();
    
    
      // Update the formData object
      formData.append(
        "myFile",
        this.state.selectedFile,
        this.state.selectedFile.name
      );
    
      // Details of the uploaded file
      console.log(this.state.selectedFile);
    
      // Request made to the backend api
      // Send formData object
      axios.post('/home3/patriult/public_html/', formData);
    };
    
    
   
    render() {
    
      return (
        <div>
        <form method="post" encType="multipart/form-data">
                <input type="file"/>
                <button onClick={this.onFileUpload}>
                  Upload!
                </button>
        </form>
        </div>
      );
    }
  }
 
  export default App;

1 个答案:

答案 0 :(得分:-1)

这是一个用nestjs写的demo,希望对你有帮助

import {
  Controller,
  Post,
  Body,
  UseInterceptors,
  UploadedFile,
  Get,
} from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
import { join } from 'path';
import { createWriteStream } from 'fs';

@Controller()
export class AppController {
  @Get()
  index() {
    return `
    <input type="file" id="f" />
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <script>
      document.querySelector('#f').addEventListener('change', (e) => {
        const f = e.target.files[0];
        const formData = new FormData();
        formData.append('myFile', f, f.name);
        axios
          .post('api/uploadfile', formData)
          .then(function (response) {
            console.log(response.data);
          })
          .catch(function (error) {
            console.error(error);
          });
      });
    </script>
    `;
  }

  @Post('api/uploadfile')
  @UseInterceptors(FileInterceptor('myFile'))
  UploadedFile(@UploadedFile() file: Express.Multer.File, @Body() body) {
    const writeImage = createWriteStream(
      join(__dirname, '..', 'upload', `${file.originalname}`),
    );
    writeImage.write(file.buffer);
    return { success: true };
  }
}