Reputation: 415
I am looking for an example of an HTTP Triggered Azure function that uploads 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
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
local.settings.json
."Host": {
"CORS": "*"
}
[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");
}
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;
Upvotes: 4