Save MultipartFileData file to disk

后端 未结 1 2085
灰色年华
灰色年华 2021-02-14 12:55

I have the bellow code which I have seen in other threads here, but nowhere does it actually show how to save a MultipartFileData file to disk once you have it.

         


        
1条回答
  •  无人共我
    2021-02-14 13:23

    Here is the sample for saving file in server. Hope this will help you.

    public class TestController : ApiController
    {
        const string StoragePath = @"T:\WebApiTest";
        public async Task 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");
        }
    }
    

    0 讨论(0)
提交回复
热议问题