-1

I'm trying to use FormData to upload an image and save it to a specific folder on my localhost. I can see that the data is there as Console Log shows me the name and other info. I think the problem is with axios.post since console is telling me the upload location on my localhost is not found. Just not sure what to do about it.

Here is my App.js file:

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;
  • Does this answer your question? [How to post a file from a form with Axios](https://stackoverflow.com/questions/43013858/how-to-post-a-file-from-a-form-with-axios) – antyrat Jul 15 '21 at 21:25
  • Not really, it looks like i'm doing what they say but I still get the console telling me file not found. – Patrick Brault Jul 16 '21 at 01:16
  • and did you set correct `Content-Type` as well? I don't see it in code you provided – antyrat Jul 16 '21 at 01:18
  • I added it but it changed nothing. I added 'Content-Type': 'multipart/form-data' – Patrick Brault Jul 16 '21 at 01:36
  • 1
    Do not manually add `'Content-Type':'multipart/form-data'` when you send FormData data – januw a Jul 16 '21 at 02:32
  • Doesn't look like there's anything wrong with your client-side code (though you should revert to your first version without `Content-type` header; let the browser figure that out for you). I'd say the issue is in your server-side code or the relative URL `api/uploadFile`. Use your browser's dev-tools _Network_ panel to see exactly where the request is going. Verify that it is the correct URL – Phil Jul 16 '21 at 02:46
  • Ugh this stinks, I tried multiple different ways of doing this and still get the same error: xhr.js:177 POST http://localhost:3000/ 404 (Not Found). If the code is correct and it is some server setting, how can I figure that out? – Patrick Brault Jul 16 '21 at 16:44
  • I added the code to my hostgator web page. It works and console throws no errors but still no file is uploaded to server. Here is the url to see this code in action, https://patrickbrault.me/ I can't figure it out and its bugging me bad! – Patrick Brault Jul 16 '21 at 17:36
  • You appear to be trying to post to a filesystem path. That will not work. You need a server-side process to handle file uploads, something like Express, Django, PHP, etc. Since you now have a `
    ` your button element should be `type="button"` to prevent the form from submitting normally
    – Phil Jul 16 '21 at 22:46
  • I am trying to post to a filesystem path. Thought axios could handle it, guess not. – Patrick Brault Aug 02 '21 at 20:38

1 Answers1

-1

This is a demo written using nestjs, I hope it will help you

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 };
  }
}

januw a
  • 2,056
  • 5
  • 18
  • 39