ASP.NET Web API 文件另存为“BodyPart_3ded2bfb-40be-4183-b789-9301f93e90af" [英] ASP.NET Web API File saved as "BodyPart_3ded2bfb-40be-4183-b789-9301f93e90af"

查看:15
本文介绍了ASP.NET Web API 文件另存为“BodyPart_3ded2bfb-40be-4183-b789-9301f93e90af"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 ASP.NET Web API 上传文件.我在 RC 之前已经这样做了,但由于某种原因,文件被保存为BodyPart_3ded2bfb-40be-4183-b789-9301f93e90af"而不是文件名.下面的文件名变量也返回此正文部分字符串而不是文件名.我似乎无法弄清楚我哪里出错了.任何帮助表示赞赏.

I'm uploading files using the ASP.NET Web API. I've done this before the RC but for some reason the file is being saved as "BodyPart_3ded2bfb-40be-4183-b789-9301f93e90af" instead of the file name. The filename variable below returns this bodypart string too instead of the file name. I can't seem to figure out where I'm going wrong. Any help is appreciated.

客户端代码:

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

控制器:

    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());

文件看起来像:

推荐答案

这是我们做出的一个有意识的更改——采用 Content-Disposition 标头字段中提供的文件名被认为存在安全风险,因此我们现在计算您所看到的文件名.

That was a concious change we made -- it was considered a security risk to take the file name provided in the Content-Disposition header field and so instead we now compute a file name which is what you are seeing.

如果您想自己控制服务器本地文件名,那么您可以从 MultipartFormDataStreamProvider 派生并覆盖 GetLocalFileName 以提供您想要的任何名称.但请注意,这样做可能存在安全考虑.

If you want to control the server local file name yourself then you can derive from MultipartFormDataStreamProvider and override GetLocalFileName to provide whatever name you want. Note though that there may be security considerations doing so.

希望这会有所帮助,

亨里克

这篇关于ASP.NET Web API 文件另存为“BodyPart_3ded2bfb-40be-4183-b789-9301f93e90af"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆