2012-12-05 12 views
16

W jaki sposób chciałbym użyć MultipartFormDataStreamProvider i Request.Content.ReadAsMultipartAsync w ApiController?przy użyciu MultipartFormDataStreamProvider i ReadAsMultipartAsync

Mam googled kilka samouczków, ale nie mogę uzyskać żadnego z nich do pracy, im przy użyciu .net 4.5.

To, co obecnie otrzymała:

public class TestController : ApiController 
{ 
    const string StoragePath = @"T:\WebApiTest"; 
    public async void Post() 
    { 
     if (Request.Content.IsMimeMultipartContent()) 
     { 
      var streamProvider = new MultipartFormDataStreamProvider(Path.Combine(StoragePath, "Upload")); 
      await Request.Content.ReadAsMultipartAsync(streamProvider); 
      foreach (MultipartFileData fileData in streamProvider.FileData) 
      { 
       if (string.IsNullOrEmpty(fileData.Headers.ContentDisposition.FileName)) 
       { 
        throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotAcceptable, "This request is not properly formatted")); 
       } 
       string fileName = fileData.Headers.ContentDisposition.FileName; 
       if (fileName.StartsWith("\"") && fileName.EndsWith("\"")) 
       { 
        fileName = fileName.Trim('"'); 
       } 
       if (fileName.Contains(@"/") || fileName.Contains(@"\")) 
       { 
        fileName = Path.GetFileName(fileName); 
       } 
       File.Copy(fileData.LocalFileName, Path.Combine(StoragePath, fileName)); 
      } 
     } 
     else 
     { 
      throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotAcceptable, "This request is not properly formatted")); 
     } 
    } 
} 

otrzymuję wyjątek

Nieoczekiwany koniec strumienia wieloczęściowej MIME. Komunikat wieloczęściowy MIME nie jest kompletny w postaci .

po uruchomieniu await task;. Czy ktoś ma pojęcia, co robię źle lub mieć działający przykład w normalnym projekcie asp.net za pomocą api sieci web.

+0

Jeśli 't.IsFaulted' ma wartość true, oznacza to, że był wyjątek i zostanie zapełniony we właściwości' Exception'. Zobacz, czym był wyjątek. Ewentualnie po prostu "czekaj na zadanie", aby uprościć kod, a między innymi ponownie wyświetli wyjątki. – Servy

+0

po zastąpieniu ContinueWith i zdaniem if po "oczekuj zadania"; Otrzymuję "Nieoczekiwany koniec wieloczęściowego strumienia MIME. Komunikat wieloczęściowy MIME nie jest kompletny." – Peter

+0

myślę następujące Post może pomóc http://stackoverflow.com/questions/17177237/webapi-ajax-formdata-upload-with-extra-parameters – user2880706

Odpowiedz

28

postanowiłem błąd, nie rozumiem, co to ma do czynienia z końcem wieloczęściowy strumienia, ale tutaj jest kod roboczych:

public class TestController : ApiController 
{ 
    const string StoragePath = @"T:\WebApiTest"; 
    public async Task<HttpResponseMessage> Post() 
    { 
     if (Request.Content.IsMimeMultipartContent()) 
     { 
      var streamProvider = new MultipartFormDataStreamProvider(Path.Combine(StoragePath, "Upload")); 
      await Request.Content.ReadAsMultipartAsync(streamProvider); 
      foreach (MultipartFileData fileData in streamProvider.FileData) 
      { 
       if (string.IsNullOrEmpty(fileData.Headers.ContentDisposition.FileName)) 
       { 
        return Request.CreateResponse(HttpStatusCode.NotAcceptable, "This request is not properly formatted"); 
       } 
       string fileName = fileData.Headers.ContentDisposition.FileName; 
       if (fileName.StartsWith("\"") && fileName.EndsWith("\"")) 
       { 
        fileName = fileName.Trim('"'); 
       } 
       if (fileName.Contains(@"/") || fileName.Contains(@"\")) 
       { 
        fileName = Path.GetFileName(fileName); 
       } 
       File.Move(fileData.LocalFileName, Path.Combine(StoragePath, fileName)); 
      } 
      return Request.CreateResponse(HttpStatusCode.OK); 
     } 
     else 
     { 
      return Request.CreateResponse(HttpStatusCode.NotAcceptable, "This request is not properly formatted"); 
     } 
    } 
} 
+2

możemy zobaczyć przykład tego, jak ta metoda nazywa się post przez klienta? –

+0

Otrzymuję następujący błąd w linii zaczyna się od 'await': " Dostęp do BinaryRead, Form, Files lub InputStream został uzyskany, zanim pamięć wewnętrzna została wypełniona przez wywołującego HttpRequest.GetBufferedInputStream. " Czy masz jakieś sugestie na temat tego, co może być przyczyną? – ciuncan

+0

@ciuncan sprawdź odpowiedź na http://stackoverflow.com/questions/17602845/post-error-either-binaryread-form-files-lub-inputstream-was-accessed-pl- może ci pomóc! – Peter

6

najpierw należy zdefiniować enctype do wieloczęściowy/form-data w nagłówku żądania ajax.

[Route("{bulkRequestId:int:min(1)}/Permissions")] 
    [ResponseType(typeof(IEnumerable<Pair>))] 
    public async Task<IHttpActionResult> PutCertificatesAsync(int bulkRequestId) 
    { 
     if (Request.Content.IsMimeMultipartContent("form-data")) 
     { 
      string uploadPath = HttpContext.Current.Server.MapPath("~/uploads"); 

      var streamProvider = new MyStreamProvider(uploadPath); 

      await Request.Content.ReadAsMultipartAsync(streamProvider); 

      List<Pair> messages = new List<Pair>(); 
      foreach (var file in streamProvider.FileData) 
      { 
       FileInfo fi = new FileInfo(file.LocalFileName); 
       messages.Add(new Pair(fi.FullName, Guid.NewGuid())); 
      } 

      //if (_biz.SetCertificates(bulkRequestId, fileNames)) 
      //{ 
      return Ok(messages); 
      //} 
      //return NotFound(); 
     } 
     return BadRequest(); 
    } 
} 




public class MyStreamProvider : MultipartFormDataStreamProvider 
{ 
    public MyStreamProvider(string uploadPath) : base(uploadPath) 
    { 
    } 
    public override string GetLocalFileName(HttpContentHeaders headers) 
    { 
     string fileName = Guid.NewGuid().ToString() 
      + Path.GetExtension(headers.ContentDisposition.FileName.Replace("\"", string.Empty)); 
     return fileName; 
    } 
} 
Powiązane problemy