File upload with ASP.Net Core 2.0 Web API and React.js

后端 未结 4 517
忘了有多久
忘了有多久 2021-02-03 13:30

I\'m new to both react.js and ASP.Net core 2.0. And now writing a project using ASP.Net core 2.0 as back end API and react.js as application interface (front end). I\'d like to

4条回答
  •  臣服心动
    2021-02-03 13:51

    [Route("api/[controller]")]
    [ApiController]
    public class UploaderController : ControllerBase
    {
        [HttpPost]
        public dynamic UploadJustFile(IFormCollection form)
        {
            try
            {
                foreach (var file in form.Files)
                {
                    string path = Path.Combine(@"C:\uploadFiles");
                    using (var fs = new FileStream(Path.Combine(path, file.FileName), FileMode.Create))
                    {
                        file.CopyToAsync(fs);
                    }
                    UploadFile(file);
                }
    
                return new { Success = true };
            }
            catch (Exception ex)
            {
                return new { Success = false, ex.Message };
            }
        }
    

    and in UI use this

    uploadJustFile(e) {
     e.preventDefault();
     let state = this.state;
    
    this.setState({
      ...state,
      justFileServiceResponse: 'Please wait'
    });
    
    if (!state.hasOwnProperty('files')) {
      this.setState({
        ...state,
        justFileServiceResponse: 'First select a file!'
      });
      return;
    }
    
    let form = new FormData();
    
    for (var index = 0; index < state.files.length; index++) {
      var element = state.files[index];
      form.append('file', element);
    }
    debugger;
    axios.post('/api/uploader', form)
      .then((result) => {
        let message = "Success!"
        if (!result.data.success) {
          message = result.data.message;
        }
        this.setState({
          ...state,
          justFileServiceResponse: message
        });
      })
      .catch((ex) => {
        console.error(ex);
      });
     }
    

提交回复
热议问题