Post 文本值和通过 Web 上传图像 Api 2 C#

Post Text values and upload an image by Web Api 2 C#

我正在尝试将一些数据保存到我的数据库并同时使用 Web Api 上传图像。

我没能做到这一点,因为我不能同时发送 multipart/from 和 JSON。我收到此错误:

request entity's media type 'multipart/form-data' is not supported for this resource.

这是我的代码:

public IHttpActionResult Post([FromBody]Post userpost)
{
   Upload upload = new Upload();
   int postid = Convert.ToInt32(postDB.AddPost(userpost));                   
   var filename = postid + "_"+Guid.NewGuid().ToString();
   upload.UploadFile(filename, Request);
   return Ok(HttpStatusCode.Accepted);
}

public class Upload:IUpload
{
    private const string Container = "images";

    public async Task<bool> UploadFile(string filename, HttpRequestMessage Request)
    {
        var accountName = ConfigurationManager.AppSettings["storage:account:name"];

        var accountKey = ConfigurationManager.AppSettings["storage:account:key"];
        var storageAccount = new CloudStorageAccount(new StorageCredentials(accountName, accountKey), true);
        CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();

        CloudBlobContainer imagesContainer = blobClient.GetContainerReference(Container);

        var provider = new AzureImages(imagesContainer,filename);

        try
        {
            await Request.Content.ReadAsMultipartAsync(provider);
        }
        catch (Exception ex)
        {
            return false;
        }

        if (string.IsNullOrEmpty(filename))
        {
            return false;
        }

        return true;
    }
}
}

我正在使用 Postman 对其进行测试 提前致谢。

创建一个视图模型来处理您发布的所有信息。

public class CombinedPostAndImage
{
    /* your post properties */
    public intProperty1 { get;set; }
    public string Propert2 { get;set; }
    ...
    public string FileName { get; set; }
    /* this example is using a Base64String
    public string FileBody { get; set; }
}

更改您的控制器操作以接受这种新类型。

public IHttpActionResult Post(CombinedPostAndImage combinedPost)
{
  /* create your Post from the combinedPost  */
    var post = new Post
    {
        post.Property1 = combinedPost.Property1,
        /* more properties */
    };

    int postid = Convert.ToInt32(postDB.AddPost(userpost));

    var filename= string.Format("{0}_{1}", postid, Guid.NewGuid().ToString());

        //Convert Base64 Encoded string to Byte Array.
    using (var ms = new MemoryStream(Convert.FromBase64String(combinedPost.FileBody)))
    {
        var uploader = new Upload();
        uploader.UploadFile(filename, ms);
    }
}

根据您的更新,我会更改 UploadFile 方法以获取流。喜欢

public async Task<bool> UploadFile(string filename, Stream uploadStream)
{       
   var accountName = ConfigurationManager.AppSettings["storage:account:name"];

    var accountKey = ConfigurationManager.AppSettings["storage:account:key"];
    var storageAccount = new CloudStorageAccount(new StorageCredentials(accountName, accountKey), true);
    CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
    CloudBlobContainer imagesContainer = blobClient.GetContainerReference(Container);

    CloudBlockBlob blockBlob = imagesContainer.GetBlockBlobReference(filename);

    blockBlob.UploadFromStream(uploadStream);
}  

我不熟悉 Azure SDK,但从在线文档来看,您可能想要这样的东西。

我不会将我的 Azure 上传器绑定到请求流。我还将 Upload(er) class 传递给我的控制器的构造函数,因为它是一个必需的依赖项,可以通过 IoC 容器来满足。