Angular 5文件上传到ASP NET的块返回MIME多部分流的意外结束。 MIME多部分消息未完成

时间:2018-03-23 20:44:01

标签: asp.net-mvc angular asp.net-web-api multipartform-data fileapi

所以,我试图使用Angular 5和fileapi

以块的形式上传大文件

这就是我的请求:

const formData: FormData = new FormData();
formData.append('fileKey', this.fileToUpload, this.fileToUpload.name);
FileAPI.upload({
  url: 'http://localhost:22166/api/lbx/upload',
  headers: { 'authorization' : `Bearer ${this._svc.getToken()}`,
    // 'Content-Disposition': `attachment; filename=${this.fileToUpload.name}; name=zip},
    files: {
      file: formData
    },
    // formData: true,
    // chunkSize: 1.0 * FileAPI.MB,
    progress: function (evt){
      console.log((evt.loaded / evt.total) * 100);
    },
    complete: function (err, xhr){
      if (err) {
        const message = JSON.parse(xhr.responseText).ExceptionMessage;
        parent.saving = false;
        parent.snack(message);
      } else {
        console.log('completed');
      }
    }
});

这就是我Post的样子:

[HttpPost]
    [Route("lbx/upload")]
    [EnableCors(origins: "*", headers: "*", methods: "*", SupportsCredentials = true)]
    public async Task<IHttpActionResult> UploadLBXProject()
    {
      try
      {
        if (!Request.Content.IsMimeMultipartContent("form-data"))
        {
          const string errorMsg = "Request content is not MIME multipart content and is unsupported.";
          AppEventLog.Error(string.Format(errorMsg));
          return StatusCode(HttpStatusCode.UnsupportedMediaType);
        }

        var root = HttpContext.Current.Server.MapPath("~/App_Data");
        var result = await Request.Content.ReadAsMultipartAsync(new MultipartFormDataStreamProvider(root)); //here it fails
        var uploadedFile = result.FileData.First();
        var originalFileName = JsonConvert.DeserializeObject(uploadedFile.Headers.ContentDisposition.FileName).ToString();
        var uploadedFileInfo = new FileInfo(uploadedFile.LocalFileName);

        var part = ".part_1";

        //Get the orignal file name that was on the client side for "BodyPart_"
        var newZipFileName = uploadedFileInfo.FullName.Replace(uploadedFileInfo.Name, originalFileName + part);
        var regex = new Regex("\\d+");

        //If a zip file with the original name already exists, rename it
        while (File.Exists(newZipFileName))
        {
          var s = newZipFileName.Split('.');
          var np = ".part_" + (int.Parse(regex.Match(s[s.Length - 1]).Value) + 1);
          newZipFileName = newZipFileName.Replace(part, np);
          part = np;
        }

        var extractedFolderName = newZipFileName.Replace(".zip", "");

        if (Directory.Exists(extractedFolderName))
        {
          Directory.Delete(extractedFolderName, true);
        }

        File.Move(uploadedFileInfo.FullName, newZipFileName);

        AppEventLog.Info("upload of zip file finished");

        var response = new HttpResponseMessage(HttpStatusCode.OK);
        response.Content.Headers.Add("Access-Control-Expose-Headers", "X-Last-Known-Byte");

        return ResponseMessage(response);
      }
      catch (Exception e)
      {
        //Delete the partially uploaded file if exception occured or if the user aborted
        var uploadedFilesPath = HttpContext.Current.Server.MapPath("~/App_Data/");

        foreach (var fileInfo in new DirectoryInfo(uploadedFilesPath)
                                    .GetFiles())
        {
          File.Delete(fileInfo.FullName);
        }
        return InternalServerError(e);
      }
    }

这可以在不使用fileapi但使用此客户端代码的情况下正常工作。

uploadLBX(file: File): Observable<any> {
    const formData: FormData = new FormData();
    formData.append('fileKey', file, file.name);
    const query = this._config.WEB_API_BASE_URL + this._config._api_urls.post.lbx.uploadzip;
    const headers = this.getHeaders();
    return this._http.post(query, formData, { headers: headers })
               .do(data => console.log(`file uploaded successfully`))
               .catch(this.handleError);
  }

但是,它不适用于大文件,因为我的web.config已经具有请求的最大值:

<system.web>
    <compilation debug="true" targetFramework="4.5.2" />
    <httpRuntime targetFramework="4.5.2" maxRequestLength="2147483647" />
  </system.web>

例外:

  

MIME多部分流的意外结束。 MIME多部分消息不是   完整。

我该怎么办?

由于

修改 添加了网络请求

enter image description here

0 个答案:

没有答案