csharp ASP.NET WebApi Post File操作

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了csharp ASP.NET WebApi Post File操作相关的知识,希望对你有一定的参考价值。

public async Task<HttpResponseMessage> PostFile()
{
    if (!Request.Content.IsMimeMultipartContent())
    {
        throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
    }

    Stream reqStream = Request.Content.ReadAsStreamAsync().Result;
    MemoryStream tempStream = new MemoryStream();
    reqStream.CopyTo(tempStream);

    tempStream.Seek(0, SeekOrigin.End);
    StreamWriter writer = new StreamWriter(tempStream);
    writer.WriteLine();
    writer.Flush();
    tempStream.Position = 0;


    StreamContent streamContent = new StreamContent(tempStream);
    foreach (var header in Request.Content.Headers)
    {
        streamContent.Headers.Add(header.Key, header.Value);
    }

    var provider = new InMemoryMultipartFormDataStreamProvider();

    try
    {
        var attachments = new List<Attachment>();

        await streamContent.ReadAsMultipartAsync(provider).ContinueWith(t =>
        {
            foreach (var item in provider.Files)
            {

                var file = item.ReadAsByteArrayAsync().Result;
                var attachment = new Attachment
                {
                    Name = FixFilename(item.Headers.ContentDisposition.FileName)
                };
              
               
                attachment.Save();
                attachments.Add(attachment);

                var basePath = System.Web.Hosting.HostingEnvironment.MapPath("~/App_Data/Attachments/" + attachment.Id);// + "/" + ;
                if (!Directory.Exists(basePath))
                {
                    Directory.CreateDirectory(basePath);
                }

                var fileName = attachment.Id + "-" + attachment.Name;

                File.WriteAllBytes(Path.Combine(basePath, fileName), file);
            }
        });
        
        reqStream.Close();
        tempStream.Close();
        writer.Close();

        return new HttpResponseMessage()
        {
            Content = new ObjectContent(attachments.GetType(), attachments, new JsonMediaTypeFormatter())
        };
    }
    catch (System.Exception e)
    {
        return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
    }
}

以上是关于csharp ASP.NET WebApi Post File操作的主要内容,如果未能解决你的问题,请参考以下文章

csharp 从ASP.NET WebAPI控制器以camelCase格式返回JSON数据。

csharp 对于asp.net WebAPI客户端。启用cookie并以任何方式信任HTTPS认证。

选择 webApi 模板时如何将 ASP.Net 身份添加到 Asp.Net Core?

[Asp.Net WebApi]WebApi入门

[Asp.Net WebApi]WebApi入门

asp.net 如何变成 MVC 或 WebApi?