web-dev-qa-db-ja.com

"BodyPart_3ded2bfb-40be-4183-b789-9301f93e90af"として保存されたASP.NET Web APIファイル

ASP.NET Web APIを使用してファイルをアップロードしています。 RCの前にこれを行いましたが、何らかの理由でファイルがファイル名ではなく「BodyPart_3ded2bfb-40be-4183-b789-9301f93e90af」として保存されています。以下のfilename変数は、ファイル名の代わりにこのbodypart文字列も返します。どこが間違っているのかわからないようです。どんな助けでもありがたいです。

クライアントコード:

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

ファイルは次のようになります。

enter image description here

34
Rivka

これは、私たちが行った重要な変更でした。Content-Dispositionヘッダーフィールドで提供されたファイル名を取得することはセキュリティ上のリスクと考えられていたため、代わりに、表示されているファイル名を計算します。

サーバーのローカルファイル名を自分で制御する場合は、MultipartFormDataStreamProviderから派生し、GetLocalFileNameをオーバーライドして、任意の名前を指定できます。ただし、セキュリティに関する考慮事項がある場合があります。

お役に立てれば、

ヘンリック

ASP.NET Web API RCで動作するようにチュートリアルのコードを更新しました。実際、Henrikが言及したように、Content-Dispositionはファイル名として使用されなくなりました。投稿の下部にあるソースファイルを参照してください- http://www.strathweb.com/2012/04/html5-drag-and-drop-asynchronous-multi-file-upload-with-asp-net -webapi /

MultipartFormDataStreamProviderには、RCを切断しなかった変更がさらにあるため、より柔軟になったことに注意してください。 Henrikはそれらについてここにブログを書いた- http://blogs.msdn.com/b/henrikn/archive/2012/04/27/asp-net-web-api-updates-april-27.aspx

編集:私は、Web API RTMでファイルをアップロードする新しい改善された方法についてブログを書いているので、うまくいけば物事を整理するのに役立つはずです- http ://www.strathweb.com/2012/08/a-guide-to-asynchronous-file-uploads-in-asp-net-web-api-rtm/

18
Filip W

ここで、私にとってこの作品

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

その後

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

おかげで、

12
VietNguyen