【问题标题】:react axios upload file and save to serverreact axios上传文件并保存到服务器
【发布时间】:2021-07-15 21:24:35
【问题描述】:

我正在尝试使用 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;

【问题讨论】:

  • 这能回答你的问题吗? How to post a file from a form with Axios
  • 不是真的,看起来我正在按照他们说的做,但我仍然让控制台告诉我找不到文件。
  • 您是否也设置了正确的Content-Type?我在您提供的代码中没有看到它
  • 我添加了它,但它什么也没改变。我添加了 'Content-Type': 'multipart/form-data'
  • 发送FormData数据时不要手动添加'Content-Type':'multipart/form-data'

标签: reactjs axios form-data


【解决方案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 };
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-28
    • 2018-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多