使用asp.net web api获取黑色/无图像

本文关键字:黑色 图像 获取 api asp net web 使用 | 更新日期: 2023-09-27 18:23:34

我正在从控制台应用程序向asp.net web api发布一个图像。我在文件夹中得到一个文件,但图像是黑色的(没有图像)。我的代码有问题吗?

public class UploadController : ApiController
{
    [System.Web.Mvc.HttpPost]
    public string Upload()
    {
        var request = HttpContext.Current.Request;
        var filePath = Path.Combine(HttpContext.Current.Server.MapPath("~/Uploads/"), request.Headers["filename"]);
        try
        {
            using (var fs = new System.IO.FileStream(filePath, System.IO.FileMode.Create))
            {
                request.InputStream.CopyTo(fs);
            }
        }
        catch (Exception e)
        {
            return e.Message;
        }
        return "uploaded";
    }
}

编辑

我的控制台应用程序http://pastebin.com/VsnDMYpb

使用asp.net web api获取黑色/无图像

试试这个。这对我有用。我用它上传多个文件

var httpRequest = HttpContext.Current.Request;
foreach (string file in httpRequest.Files)
{
    var postedFile = httpRequest.Files[file];
    var filePath = HttpContext.Current.Server.MapPath("~/Uploads/" + postedFile.FileName);
    postedFile.SaveAs(filePath);
}      

使用Request.Content.ReadAsMultipartAsync

public Task<IQueryable<HDFile>> Post()
{
    try
    {
        var uploadFolderPath = HostingEnvironment.MapPath("~/App_Data/" + UploadFolder);
        log.Debug(uploadFolderPath);
        if (Request.Content.IsMimeMultipartContent())
        {
            var streamProvider = new WithExtensionMultipartFormDataStreamProvider(uploadFolderPath);
            var task = Request.Content.ReadAsMultipartAsync(streamProvider).ContinueWith<IQueryable<HDFile>>(t =>
            {
                if (t.IsFaulted || t.IsCanceled)
                {
                    throw new HttpResponseException(HttpStatusCode.InternalServerError);
                }
                var fileInfo = streamProvider.FileData.Select(i =>
                {
                    var info = new FileInfo(i.LocalFileName);
                    return new HDFile(info.Name, Request.RequestUri.AbsoluteUri + "?filename=" + info.Name, (info.Length / 1024).ToString());
                });
                return fileInfo.AsQueryable();
            });
            return task;
        }
        else
        {
            throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotAcceptable, "This request is not properly formatted"));
        }
    }
    catch (Exception ex)
    {
        log.Error(ex);
        throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.BadRequest, ex.Message));
    }
}

我从这篇文章中得到的代码