mvc multiple files c#-4.0 multipart multifile-uploader

c#-4.0 - multiple - upload file spring mvc 4



Guarde el archivo MultipartFileData en el disco (1)

Tengo el siguiente código que he visto en otros hilos aquí, pero en realidad no muestra cómo guardar un archivo MultipartFileData en el disco una vez que lo tienes.

[HttpPost] public Task<HttpResponseMessage> PostFormData() { // Check if the request contains multipart/form-data. if (!Request.Content.IsMimeMultipartContent()) { throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType); } string root = HttpContext.Current.Server.MapPath(Settings.AssetImageTempStorage); var provider = new MultipartFormDataStreamProvider(root); // Read the form data and return an async task. var task = Request.Content.ReadAsMultipartAsync(provider). ContinueWith<HttpResponseMessage>(t => { if (t.IsFaulted || t.IsCanceled) { Request.CreateErrorResponse(HttpStatusCode.InternalServerError, t.Exception); } // This illustrates how to get the file names. foreach (MultipartFileData file in provider.FileData) { // HOW DO I SAVE THIS FILE TO DISK HERE ??? Trace.WriteLine(file.Headers.ContentDisposition.FileName); Trace.WriteLine("Server file path: " + file.LocalFileName); } return Request.CreateResponse(HttpStatusCode.OK); }); return task; }

Gracias, Andrei


Aquí está la muestra para guardar el archivo en el servidor. Espero que esto te ayudará.

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"); } }