OuterSpace
OuterSpace

Reputation: 415

HTTP Triggered Azure function to upload file

I am looking for an example of an HTTP Triggered Azure function that uploadsenter image description here a file in C#.

The front end is made in React:

const onSave = async () => {
    console.log(fileToUpload)
    if (Object.keys(fileToUpload).length === 0) {
        alert("Errore, selezionare un file per l'upload!");
    }
    else {
        const requestOptions = {
            method: 'POST',
            headers: { 'Content-Type': 'application/json'},
            body: { fileToUpload }
        };
        fetch('http://localhost:7071/api/upload', requestOptions)
            .then(response => console.log(response)
            );

In the attached image you can find the toUpload object

Upvotes: 3

Views: 3957

Answers (1)

Jim Xu
Jim Xu

Reputation: 23111

If you want to send your file to Azure function in your react application, you can create FormData and save file in the form data then send the form data to azure function. The detailed steps are as below

  • Server
  1. Configure CORS. Please add the following code in your local.settings.json.
"Host": {
    "CORS": "*"
  }
  1. Code
 [FunctionName("Http")]
        public static async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
            ILogger log, ExecutionContext context)
        {

            var files = req.Form.Files;

            foreach (var file in files) {
                log.LogInformation("The file name is : " + file.FileName);
            
            }

            return new OkObjectResult("OK");

        }
  • Client
import React, { Component } from 'react'
import './App.css';\
import fetch from 'node-fetch'

class App extends Component {
import React, { Component } from 'react'
import './App.css'
import fetch from 'node-fetch'

class App extends Component {

  constructor(props) {
    super(props);
    this.state = {
      selectedFile: null
    }

  }
 // get file
  onChangeHandler = event => {
    console.log(event.target.files[0])
    this.setState({
      selectedFile: event.target.files[0],
      loaded: 0,
    })

  }
 //send file
  onClickHandler = async () => {
    const data = new FormData()
    data.append('file', this.state.selectedFile)
    await fetch("http://localhost:7071/api/Http", { method: 'post', body: data })
      .then(res => console.log(res))
      .catch(error => console.error(error))



  }
  render() {
    return (

      <div className="container">
        <div className="row">
          <div className="col-md-6">
            <div className="form-group files">
              <label>Upload Your File </label>
              <input type="file" name="file" onChange={this.onChangeHandler} />
              <button type="button" className="btn btn-success btn-block" onClick={this.onClickHandler}>Upload</button>
            </div>
          </div>
        </div>
      </div>
    )
  }
}

export default App;

enter image description here

enter image description here

Upvotes: 4

Related Questions