如何在使用multipart时从图像中删除内容

时间:2017-06-07 04:57:20

标签: c# asp.net-web-api filestream multipartform-data

所以我通过使用多部分表单数据在我的Web API中创建了一个上传器,但问题是当我从文件流中保存我的图片时它还给了我这里的内容

 -----------------------------7e1e364095c
Content-Disposition: form-data; name="file"; filename="C:\Users\kewin\Downloads\windows 10 pro.jpg"
Content-Type: image/jpeg

 the binary starts from here        

如果我删除thoose 4行我可以看我的图片所以有任何方法删除它所以我只剩下图片

    public async Task<IHttpActionResult> UploadImage(string fileName = "")
    {
        if (fileName == "")
        {
            fileName = Guid.NewGuid().ToString();
        }
            if (!Request.Content.IsMimeMultipartContent("form-data"))
        {
            return BadRequest("Could not find file to upload");
        }
        var provider = await Request.Content.ReadAsMultipartAsync(new InMemoryMultipartFormDataStreamProvider());

        var files = provider.Files;
        var uploadedFile = files[0];
        var extension = ExtractExtension(uploadedFile);
        var contentType = uploadedFile.Headers.ContentType.ToString();
        var savePath = ConfigurationManager.AppSettings["savePath"];
        var file = string.Concat(savePath, fileName, extension);

        try
        {
            var request = HttpContext.Current.Request;
            var fileDir = file + request.Headers[""];
            using (var fs = new FileStream(fileDir, FileMode.Create))
            {
                request.InputStream.CopyTo(fs);
            }
            return Ok();
        }

        catch (StorageException e)
        {
            return BadRequest(e.Message);
        }

        try
        {
                var fileInfo = new UploadedFileInfo
            {
                FileName = fileName,
                FileExtension = extension,
                ContentType = contentType,
                FilePath = savePath + imageFile
            };
            return Ok(fileInfo);
        }

1 个答案:

答案 0 :(得分:1)

目前,您正在阅读request.InputStream的图片数据,其中包含整个未解析的多部分内容,包括您不需要的标题。相反,您应该从您创建的InMemoryMultipartFormDataStreamProvider读取图片数据,该图片数据解析输入流并为您提供对单个上传文件的标题和数据流的简单访问。

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

var files = provider.Files;
var uploadedFile = files[0];
var extension = ExtractExtension(uploadedFile);
var contentType = uploadedFile.Headers.ContentType.ToString();
var savePath = ConfigurationManager.AppSettings["savePath"];
var file = string.Concat(savePath, fileName, extension);

try
{
    using (var fs = new FileStream(file, FileMode.Create))
    {
        await uploadedFile.CopyToAsync(fs);
    }
    return Ok();
}
....