csharp 上传文件web api 2

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了csharp 上传文件web api 2相关的知识,希望对你有一定的参考价值。

<input type="file" name="" id="" #file>
<button (click)="uploadFile(file)">upload file</button>
uploadFile(file) {
    file = file.files[0];
    let formData:FormData = new FormData();
    formData.append('uploadFile', file, file.name);
    const req = new HttpRequest("POST", "/api/file", formData, {
      reportProgress: true,
    });

    this.http.request(req).subscribe(event => {
      if (event.type === HttpEventType.UploadProgress) {
        const percentDone = Math.round(100 * event.loaded / event.total);
        console.log(`File is ${percentDone}% uploaded.`);
      } else if (event instanceof HttpResponse) {
        console.log('File is completely uploaded!');
      }

    })
  }
<system.web>
    <httpRuntime targetFramework="4.6.1" maxRequestLength="300000000" /> 
</system.web>
public class FileController : ApiController
    {
		
		public async Task<HttpResponseMessage> Post()
		{
		  if (!Request.Content.IsMimeMultipartContent())
			throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);

		  var provider = new MultipartFormDataStreamProvider(HostingEnvironment.MapPath("~/App_Data"));
		  var files = await Request.Content.ReadAsMultipartAsync(provider);
		  // Do something with the files if required, like saving in the DB the paths or whatever
		  File.WriteAllBytes(files.FileData[0].LocalFileName+".png", File.ReadAllBytes(files.FileData[0].LocalFileName));
		  File.Delete(files.FileData[0].LocalFileName);
		  return Request.CreateResponse(HttpStatusCode.OK,"ok"); ;
		}
  }

以上是关于csharp 上传文件web api 2的主要内容,如果未能解决你的问题,请参考以下文章

CSharp Web实现文件上传下载功能实例解析

CSharp 大文件上传解决方案(500M以上)

csharp实现浏览器端大文件分块上传

csharp上传大型视频文件到服务器,解决方案

csharp上传大型视频文件到服务器,解决方案

尝试将文件从一个 Web 上传到 API 时出错