簡體   English   中英

ASP.Net Web API - 同步獲取POSTed文件?

[英]ASP.Net Web API - Get POSTed file synchronously?

有沒有辦法同步處理發布到ASP.Net Web API中的控制器的上傳文件?

我已經嘗試了微軟在這里提出的過程,它按照描述工作,但是我想從Controller方法返回一個不同於Task <>的東西,以匹配我的RESTful API的其余部分。

基本上,我想知道是否有任何方法可以使這項工作:

public MyMugshotClass PostNewMugshot(MugshotData data){
    //get the POSTed file from the mime/multipart stream <--can't figure this out
    //save the file somewhere
    //Update database with other data that was POSTed
    //return a response
}

我再次使異步示例工作,但我希望在響應客戶端之前處理上傳文件的方法。

public class UploadController : ApiController
{
    public async Task<HttpResponseMessage> Post()
    {
        if (!Request.Content.IsMimeMultipartContent())
        {
            throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
        }

        var appData = HostingEnvironment.MapPath("~/App_Data");
        var folder = Path.Combine(appData, Guid.NewGuid().ToString());
        Directory.CreateDirectory(folder);
        var provider = new MultipartFormDataStreamProvider(folder);
        var result = await Request.Content.ReadAsMultipartAsync(provider);
        if (result.FileData.Count < 1)
        {
            // no files were uploaded at all
            // TODO: here you could return an error message to the client if you want
        }

        // at this stage all files that were uploaded by the user will be
        // stored inside the folder we specified without us needing to do
        // any additional steps

        // we can now read some additional FormData
        string caption = result.FormData["caption"];

        // TODO: update your database with the other data that was posted

        return Request.CreateResponse(HttpStatusCode.OK, "thanks for uploading");
    }
}

您可能會注意到上載的文件存儲在指定文件夾中,其名稱可能如下所示: BodyPart_beddf4a5-04c9-4376-974e-4e32952426ab 這是Web API團隊的一個深思熟慮的選擇,您可以根據需要進行覆蓋。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM