asp.net-mvc – 通过Web Api接收,发送文件

前端之家收集整理的这篇文章主要介绍了asp.net-mvc – 通过Web Api接收,发送文件前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试编写一个接收文件的WebApi服务,执行一个简单的操作,并将文件发回.我在从服务发送和/或接收文件时遇到问题.

我遇到的问题是从服务返回的文件比操作文件大1.5倍,例如当文件被返回时,它就像300kb而不是它应该是200kb.

我认为它被包裹或以某种方式操纵,我不确定如何正确地接收它.下面包含WebAPI服务的代码调用Web服务的方法

在,WebApi服务,当我点击该行返回Ok(bufferResult)时,该文件是一个字节[253312]

调用Web服务的方法中,在操作并返回文件之后,在行var content = stream.Result;之后,该流的长度为337754字节.

Web API服务代码

public ConversionController: APIController{
  public async Task<IHttpActionResult> TransformImage()
   {
    if (!Request.Content.IsMimeMultipartContent())
        throw new Exception();

    var provider = new MultipartMemoryStreamProvider();
    await Request.Content.ReadAsMultipartAsync(provider);

    var file = provider.Contents.First();
    var filename = file.Headers.ContentDisposition.FileName.Trim('\"');
    var buffer = await file.ReadAsByteArrayAsync();
    var stream = new MemoryStream(buffer);

// [file manipulations omitted;]
    // [the result is populated into a MemoryStream named response ]

    //debug : save memory stream to disk to make sure tranformation is successfull
    /*response.Position  = 0;
      path = @"C:\temp\file.ext";
      using (var fileStream = System.IO.File.Create(path))
      {
        saveStream.CopyTo(fileStream);
      }*/


    var bufferResult = response.GetBuffer();
    return Ok(bufferResult);
   }
}

方法调用服务

public async Task<ActionResult> AsyncConvert()
    {

    var url = "http://localhost:49246/api/conversion/transformImage";   
var filepath = "drive/file/path.ext";
    HttpContent fileContent = new ByteArrayContent(System.IO.File.ReadAllBytes(filepath));

    using (var client = new HttpClient())
    {
        using (var formData = new MultipartFormDataContent())
        {
            formData.Add(fileContent,"file","fileName");

    //call service
            var response = client.PostAsync(url,formData).Result;

            if (!response.IsSuccessStatusCode)
            {
                throw new Exception();
            }
            else
            {

                if (response.Content.GetType() != typeof(System.Net.Http.StreamContent))
                    throw new Exception();

                var stream = response.Content.ReadAsStreamAsync();
                var content = stream.Result;

                var path = @"drive\completed\name.ext";
                using (var fileStream = System.IO.File.Create(path))
                {
                    content.CopyTo(fileStream);  
                }
            }
        }


    }

    return null;
}

我还是溪流和WebApi的新手,所以我可能会遗漏一些非常明显的东西.为什么文件流的大小不同? (例如,它是否被包裹,如何打开和/或接收流)

解决方法

好的,要正确接收文件,我需要更换线路
var stream = response.Content.ReadAsStreamAsync();

var contents = await response.Content.ReadAsAsync<Byte[]>();

为绑定提供正确的类型

所以,调用服务的方法的后半部分看起来像

var content = await response.Content.ReadAsAsync<Byte[]>();
var saveStream = new MemoryStream(content);
saveStream.Position = 0;

//Debug: save converted file to disk
/*
var path = @"drive\completed\name.ext";
using (var fileStream = System.IO.File.Create(path))
{
     saveStream.CopyTo(fileStream);  
}*/
原文链接:https://www.f2er.com/aspnet/248608.html

猜你在找的asp.Net相关文章