使用Angular 6将文件上传到Web Api C#

时间:2018-12-04 13:16:26

标签: c# angular asp.net-web-api httpclient netcoreapp2.1

我有Angular CLI应用程序和Dot net core 2.0 Web API。我需要将文件从Angular上传到Web API。从Web API到服务器。当我使用Http时,它的工作正常。使用HttpClient时,它不起作用。 这是我的component.ts代码:

fileChange(event, grdvalue) {
debugger;
let fileList: FileList = event.target.files;
if (fileList.length > 0) {
  let file: File = fileList[0];
  const formData: FormData = new FormData();
  let GridName = grdvalue;

  formData.append('file', file, file.name);
  formData.append('Id', this.userId);
  formData.append('GridValue', GridName)

  this.myService.PostFileToAzure(formData).subscribe(details => {
    debugger;
  },
    (error) => {
      debugger;
    })
  }
 }

这是我的服务代码:

 PostFileToAzure(form) {
    debugger;
    var body = JSON.stringify(form);
    return this.http.post(this.baseApiURL + '/Interpretation/InterpreterFileUpload', form);
}

这是我的Web API代码:

[HttpPost("InterpreterFileUpload")]
    public async Task<IActionResult> InterpreterFileUpload()
    {
        try
        {

            var file = Request.Form.Files[0];
            HttpRequest formData = HttpContext.Request;
        }
    }

如何使用HttpClient将文件从Angular发送到Web API。 Web API中出现错误,例如“错误的Content-Type:application / json”

3 个答案:

答案 0 :(得分:1)

https://github.com/BhadraAnirban/angular_file_upload_net_core

该过程是使用FormBody中的POST调用从Angular发送base64字符串,然后在.net核心将字符串转换为字节。

注意-FormData将无法在AWS Lambda中正常工作,它将损坏文件。因此,这也是在AWS中发送邮件或上传文件的更好方法。

HTML-

<form class="row">
    <input id="{{id}}" type="file" (change)="FileSelected($event.target.files);">
</form>
<div id="hidden_upload_item" style="display: none;"></div>

打字稿-

FileSelected(files){
    this.fileData = <File>files[0];
    this.FileName = this.fileData.name;
    let reader = new FileReader();
    var selectedFile = <File>files[0];

    reader.onload = function (readerEvt: any) {
        var arrayBuffer = readerEvt.target.result.toString().split('base64,')[1];     
        document.querySelector('#hidden_upload_item').innerHTML = arrayBuffer;
        this.Proceed();
    }.bind(this);
    reader.readAsDataURL(selectedFile);

  }

  Proceed()
  {
    var item = document.querySelector('#hidden_upload_item').innerHTML;
    let formdata = new UploadFile();
    formdata.data = item;
    formdata.name = this.FileName;
    this.UploadDocument(formdata)
      .subscribe(event => {
        // Perform other operations
      }, err => {
        this.InProgress = false;
      });
  }

  UploadDocument(formData){
        const httpOptions = {
          headers: new HttpHeaders({
            'Content-Type': 'application/json'
          })
        };
        return this.http.post('/api/document/uploaddocument', formData, httpOptions);
      } 

.net核心-

[HttpPost("uploaddocument"), DisableRequestSizeLimit]
public IActionResult UploadDocument([FromBody] FileModel fileModel)
        {
            try
            {
                    var value = fileModel.Data;
                    var byteArray = Convert.FromBase64String(value);
                    var fileExtension = Path.GetExtension(fileModel.Name);
                    var fileName = fileModel.Name;

                    /// Now save in Database or AWS

                }
                return Ok();
            }
            catch (Exception e)
            {
                throw e;
            }

        }        

 public class FileModel
{
    public string Data { get; set; }
    public string Name { get; set; }
}

答案 1 :(得分:0)

在有角度的站点使用此代码

file: any;

onSelectFile($event, file) {
    this.file = file;
  }


  uploadImage() {
    if (this.file.length === 0) {
      return;
    }

    const formData = new FormData();

    for (let file of this.file)
      formData.append(file.name, file);

    const uploadReq = new HttpRequest('POST', `api/FileUpload`, formData, {
      reportProgress: true,
    });

    this.http.request(uploadReq).subscribe(event => {
      if (event.type === HttpEventType.UploadProgress) {
        this.progress = Math.round(100 * event.loaded / event.total);
      }
    });
  }

此处onSelectFile应该在这样的输入上被调用

<input #file type='file' multiple (change)="onSelectFile($event, file.files)">

在您的asp.net网站上使用此代码

[Produces("application/json")]
    [Route("api/[controller]")]
    public class FileUploadController : Controller
    {
    private IHostingEnvironment _hostingEnvironment;

    public FileUploadController(IHostingEnvironment hostingEnvironment)
    {
      _hostingEnvironment = hostingEnvironment;
    }

    [HttpPost, DisableRequestSizeLimit]
    public ObjectResult UploadFile()
    {
      try
      {
        var file = Request.Form.Files[0];
        string folderName = "Upload";
        string webRootPath = _hostingEnvironment.WebRootPath;
        string newPath = Path.Combine(webRootPath, folderName);
        if (!Directory.Exists(newPath))
        {
          Directory.CreateDirectory(newPath);
        }
        string fileName = "";
        if (file.Length > 0)
        {
          fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
          string fullPath = Path.Combine(newPath, fileName);
          using (var stream = new FileStream(fullPath, FileMode.Create))
          {
            file.CopyTo(stream);
          }
        }

        return Ok(fileName);
      }
      catch (System.Exception ex)
      {
        return BadRequest(ex.Message);
      }
    }
  }

谢谢

答案 2 :(得分:0)

我使用了@Elon Musk的解决方案,但是Request.Form.Files[0]为我提供了评估超时异常,因此为了处理它,我在.net端的Actionmethod中添加了Iformfile参数

public IActionResult UploadFile(IFormFile formfile)