使用对象上传Web API 2图像

时间:2019-02-25 07:39:41

标签: c# asp.net-web-api entity-framework-6

我要上传具有某些属性值的图像。我只能上传图片 这是我的图片上传代码:

FinishedLaunching

CustomMultipartFormDataStreamProvider类:

    [HttpPost]
    [Route("UploadImage")]
    public async Task<HttpResponseMessage> ImageUpload()
    {
        // Check whether the POST operation is MultiPart?
        if (!Request.Content.IsMimeMultipartContent())
        {
            throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
        }

        // Prepare CustomMultipartFormDataStreamProvider in which our multipart form
        // data will be loaded.
        string fileSaveLocation = HttpContext.Current.Server.MapPath("~/App_Data");
        CustomMultipartFormDataStreamProvider provider = new CustomMultipartFormDataStreamProvider(fileSaveLocation);
        List<string> files = new List<string>();

        try
        {
            // Read all contents of multipart message into CustomMultipartFormDataStreamProvider.
            await Request.Content.ReadAsMultipartAsync(provider);

            foreach (MultipartFileData file in provider.FileData)
            {
                files.Add(Path.GetFileName(file.LocalFileName));
            }

            // Send OK Response along with saved file names to the client.
            return Request.CreateResponse(HttpStatusCode.OK, files);
        }
        catch (System.Exception e)
        {
            return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
        }
    }

由邮递员enter image description here测试的功能

我想像现在那样传递到目前为止无法实现的数据

// We implement MultipartFormDataStreamProvider to override the filename of File which
// will be stored on server, or else the default name will be of the format like Body-
// Part_{GUID}. In the following implementation we simply get the FileName from 
// ContentDisposition Header of the Request Body.
public class CustomMultipartFormDataStreamProvider : MultipartFormDataStreamProvider
{
    public CustomMultipartFormDataStreamProvider(string path) : base(path) { }

    public override string GetLocalFileName(HttpContentHeaders headers)
    {
        return headers.ContentDisposition.FileName.Replace("\"", string.Empty);
    }

}

如何实现?

1 个答案:

答案 0 :(得分:0)

我可能会考虑稍微做些不同的事情以实现您想要的。在上传之前先研究一下对文件进行base64编码,然后将其作为另一文本块来处理JSON格式变得更加容易

看看这个article