将Request.Content转换为FileStream C#

时间:2015-10-15 11:16:48

标签: c# file-upload asp.net-web-api filestream

我尝试使用来自用户的Web Api接收文件,然后将文件转换为FileStream,而不将文件写入服务器(必须留在内存中)。

我有代码允许我将其写入服务器但是所有尝试将其放入FileStream而不将文件写入服务器都失败了。

public class ReceiverController : ApiController
{

    public Task<HttpResponseMessage> Upload()
    {
        HttpRequestMessage request = this.Request;

        if (!request.Content.IsMimeMultipartContent())
        {
            throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.UnsupportedMediaType));
        }

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

        var task = request.Content.ReadAsMultipartAsync(provider).
            ContinueWith<HttpResponseMessage>(o =>
        {
            FileInfo fileInfo = new FileInfo(provider.FileData.First().LocalFileName);
            string fileName = provider.FileData.First().Headers.ContentDisposition.FileName.Replace("\"", "");
            if (!File.Exists(Path.Combine(root, fileName)))
            {

                File.Move(fileInfo.FullName, Path.Combine(root, fileName));
            }

            return new HttpResponseMessage()
            {
                Content = new StringContent("File uploaded.")
            };
        });
        return task;
    }
}

1 个答案:

答案 0 :(得分:0)

fileName.PostedFile.InputStream ---给我Stream和我使用以下代码将其转换为字节数组。然后根据以下代码将字节数组转换为文件流。

BinaryReader br = new BinaryReader(fileName);
      bytary= br.ReadBytes((Int32)fileName.Length);
            for(int i = 0; i < bytary.Length; i++)
                  {
                         fileStream.WriteByte(bytary[i]);
                                }