如何使用web-api上传文件 [英] How to upload file with web-api

查看:164
本文介绍了如何使用web-api上传文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

客户端代码:

Client side code:

<form action="api/MyAPI" method="post" enctype="multipart/form-data">     
<label for="somefile">File</label>     <input name="somefile" type="file" />     
<input type="submit" value="Submit" /> 
</form>

以及如何使用mvc web-api处理上传文件,有一些示例代码?

And how to process upload file with mvc web-api,have some sample code?

推荐答案

您可以使用 ApiMultipartFormFormmatter 将文件上传到web api 2.
通过使用此库,可以定义视图模型以获取从客户端提交的参数。如:

You can use ApiMultipartFormFormmatter to upload file to web api 2. By using this library, you can define a view model to get parameters submitted from client-side. Such as:

public class UploadFileViewModel 
{
    public HttpFile Somefile{get;set;}
}

然后像这样在你的Api控制器中使用它:

And use it in your Api controller like this:

public IHttpActionResult Upload(UploadFileViewModel info)
{
    if (info == null)
    {
        info = new UploadFileViewModel();
        Validate(info);
    }

    if (!ModelState.IsValid)
        return BadRequest(ModelState);

    return Ok();
}

嵌套对象可以被这个库解析。

Nested objects can be parsed by this library.

这篇关于如何使用web-api上传文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆