簡體   English   中英

HTTP 觸發 Azure function 上傳文件

[英]HTTP Triggered Azure function to upload file

我正在尋找上傳的 HTTP 觸發 Azure function 的示例在此處輸入圖像描述 C# 中的文件。

前端是用 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)
            );

在附圖中,您可以找到上傳 object

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. 詳細步驟如下

  • 服務器
  1. 配置 CORS。 請在您的local.settings.json中添加以下代碼。
"Host": {
    "CORS": "*"
  }
  1. 代碼
 [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;

在此處輸入圖像描述

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM