ASP.NET Archivo Web API guardado como " BodyPart 3ded2bfb-40be-4183-b789-9301f93e90af"


Estoy cargando archivos usando el ASP.NET Web API. He hecho esto antes del RC, pero por alguna razón el archivo se guarda como "BodyPart_3ded2bfb-40be-4183-b789-9301f93e90af" en lugar del nombre del archivo. La variable filename de abajo devuelve esta cadena bodypart también en lugar del nombre del archivo. No sé en qué me equivoco. Cualquier ayuda es apreciada.

Código de cliente:

function upload() {
    $("#divResult").html("Uploading...");
    var formData = new FormData($('form')[0]); 
    $.ajax({
        url: 'api/files/uploadfile?folder=' + $('#ddlFolders').val(),
        type: 'POST',
        success: function (data) {
            $("#divResult").html(data);
        },
        data: formData,
        cache: false,
        contentType: false,
        processData: false
    });
}; 

Controlador:

    public Task<HttpResponseMessage> UploadFile([FromUri]string folder)
    {
        if (!Request.Content.IsMimeMultipartContent())
        {
            throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.UnsupportedMediaType));
        }

        // Save file
        MultipartFormDataStreamProvider provider = new MultipartFormDataStreamProvider(HttpContext.Current.Server.MapPath("~/Files"));
        Task<IEnumerable<HttpContent>> task = Request.Content.ReadAsMultipartAsync(provider);

        return task.ContinueWith<HttpResponseMessage>(contents =>
        {
            string filename = provider.BodyPartFileNames.First().Value;
            return new HttpResponseMessage()
          {
              Content = new StringContent(string.Format("File saved in {0}.", folder))
          };

        }, TaskScheduler.FromCurrentSynchronizationContext());

Los archivos se ven como:

introduzca la descripción de la imagen aquí

Author: Rivka, 2012-06-10

3 answers

Ese fue un cambio consciente que hicimos was se consideró un riesgo de seguridad tomar el nombre de archivo proporcionado en el campo de encabezado Content-Disposition y, en su lugar, ahora calculamos un nombre de archivo que es lo que está viendo.

Si desea controlar el nombre del archivo local del servidor usted mismo, puede derivar de MultipartFormDataStreamProvider y anular GetLocalFileName para proporcionar el nombre que desee. Sin embargo, tenga en cuenta que puede haber consideraciones de seguridad al hacerlo.

Espero que esto ayuda,

Henrik

 46
Author: Henrik Frystyk Nielsen,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-06-10 20:57:01

He actualizado el código del tutorial para que funcione con ASP.NET Web API RC. De hecho, como mencionó Henrik Content-Disposition ya no se usa un nombre de archivo. Ver los archivos de origen en la parte inferior de lahttp://www.strathweb.com/2012/04/html5-drag-and-drop-asynchronous-multi-file-upload-with-asp-net-webapi/

Tenga en cuenta que hay más cambios en MultipartFormDataStreamProvider que no hicieron el corte a la RC, por lo que ahora es aún más flexible. Henrik blogueado sobre aquellos aquí - http://blogs.msdn.com/b/henrikn/archive/2012/04/27/asp-net-web-api-updates-april-27.aspx.

EDIT: He blogueado sobre la nueva y mejorada forma de subir archivos en Web API RTM, por lo que espero que ayude a organizar las cosas - http://www.strathweb.com/2012/08/a-guide-to-asynchronous-file-uploads-in-asp-net-web-api-rtm/

 18
Author: Filip W,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-09-06 06:44:17

Aquí, este trabajo para mí

En el Controlador API

// We implement MultipartFormDataStreamProvider to override the filename of File which
// will be stored on server, or else the default name will be of the format like Body-
// Part_{GUID}. In the following implementation we simply get the FileName from 
// ContentDisposition Header of the Request Body.
public class CustomMultipartFormDataStreamProvider : MultipartFormDataStreamProvider
{
    public CustomMultipartFormDataStreamProvider(string path) : base(path) { }

    public override string GetLocalFileName(HttpContentHeaders headers)
    {
        return headers.ContentDisposition.FileName.Replace("\"", string.Empty);
    }
}

Entonces

 string root = HttpContext.Current.Server.MapPath("~/App_Data");       
 CustomMultipartFormDataStreamProvider provider = new CustomMultipartFormDataStreamProvider(root);

Gracias,

 9
Author: VietNguyen,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-12-07 02:23:16