上传文件和张贴文本输入值在一键

本文关键字:输入 一键 文本 张贴 文件 | 更新日期: 2023-09-27 18:08:47

我正在尝试为发布文件构建Asp.net web api。我找到了下面的例子https://code.msdn.microsoft.com/AngularJS-with-Web-API-22f62a6e

Web API方法为:

[RoutePrefix("api/photo")]
public class PhotoController : ApiController
{
    private IPhotoManager photoManager;
    public PhotoController()
        : this(new LocalPhotoManager(HttpRuntime.AppDomainAppPath + @"'Album"))
    {            
    }
    public PhotoController(IPhotoManager photoManager)
    {
        this.photoManager = photoManager;
    }
    // GET: api/Photo
    public async Task<IHttpActionResult> Get()
    {
        var results = await photoManager.Get();
        return Ok(new { photos = results });
    }
    // POST: api/Photo
    public async Task<IHttpActionResult> Post()
    {
        // Check if the request contains multipart/form-data.
        if(!Request.Content.IsMimeMultipartContent("form-data"))
        {
            return BadRequest("Unsupported media type");
        }
        try
        {
            var photos = await photoManager.Add(Request);
            return Ok(new { Message = "Photos uploaded ok", Photos = photos });
        }
        catch (Exception ex)
        {
            return BadRequest(ex.GetBaseException().Message);
        }
    }

和文件上传器html代码:(我添加了一个文本输入<input type="text" id="test" value="testit" />用于测试。

<form name="newPhotosForm" role="form" enctype="multipart/form-data" ng-disabled="appStatus.busy || photoManagerStatus.uploading">
    <div class="form-group" ng-hide="hasFiles">
        <label for="newPhotos">select and upload new photos</label>
        <input type="file" id="newPhotos" class="uploadFile" accept="image/*" eg-files="photos" has-files="hasFiles" multiple>
        <input type="text" id="test" value="testit" /> <!--- Added a text input for test -->
    </div>
    <div class="form-group" ng-show="hasFiles && !photoManagerStatus.uploading">
        <ul class="list-inline">
            <li><strong>files:</strong></li>
            <li ng-repeat="photo in photos"> {{photo.name}}</li>
        </ul>
        <input class="btn btn-primary" type="button" eg-upload="upload(photos)" value="upload">
        <input class="btn btn-warning" type="reset" value="cancel" />
    </div>
    <div class="form-group" ng-show="photoManagerStatus.uploading">
        <p class="help-block">uploading</p>
    </div>
</form>

JS upload函数:

function upload(photos)
{
    service.status.uploading = true;
    appInfo.setInfo({ busy: true, message: "uploading photos" });            
    var formData = new FormData();
    angular.forEach(photos, function (photo) {
        formData.append(photo.name, photo);
    });
    return photoManagerClient.save(formData)
                                .$promise
                                .then(function (result) {
                                    if (result && result.photos) {
                                        result.photos.forEach(function (photo) {
                                            if (!photoExists(photo.name)) {
                                                service.photos.push(photo);
                                            }
                                        });
                                    }
                                    appInfo.setInfo({message: "photos uploaded successfully"});
                                    return result.$promise;
                                },
                                function (result) {
                                    appInfo.setInfo({message: "something went wrong: " + result.data.message});
                                    return $q.reject(result);
                                })
                                ['finally'](
                                function () {
                                    appInfo.setInfo({ busy: false });                                            
                                    service.status.uploading = false;
                                });
}

然而,似乎增加的输入test的值不能传递给Web API代码?

上传文件和张贴文本输入值在一键

您需要添加自定义DTO/POCO类,设置值,然后将其作为参数传递给您的post方法。由于文件不是一个简单的类型,webAPI的默认MediaTypeFormatter将无法工作,因此您需要构建您的自定义MediaTypeFormatter。

示例POCO类

Public Class Attachment
{
    public string Input {get;set;}
    public byte[] Content{get;set;}
} 

自定义媒体格式化程序如下

public class CustomFormatter : MediaTypeFormatter
{
    /// <summary>
    /// 
    /// </summary>
    public CustomFormatter()
    {
        SupportedMediaTypes.Add(new MediaTypeHeaderValue("multipart/form-data"));
    }
    public override bool CanReadType(Type type)
    {
        return type == typeof(Attachment);
    }
    public override bool CanWriteType(Type type)
    {
        return false;
    }
    public async override Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
    {
        var provider = await content.ReadAsMultipartAsync();
        var modelContent = provider.Contents
            .FirstOrDefault(c => c.Headers.ContentType.MediaType == "application/json"); 
        var attachment = await modelContent.ReadAsAsync<Attachment>();
        var fileContents = provider.Contents
            .Where(c => c.Headers.ContentType.MediaType == "image/jpeg").FirstOrDefault(); // or whatever is the type of file to upload
        attachment.Content = await fileContents.ReadAsByteArrayAsync();
        return attachment;
    }
}

注册自定义媒体格式化程序:

private void ConfigureWebApi(HttpConfiguration config)
{
    //other code here
    config.Formatters.Add(new CustomFormatter());
}   

将POCO传递给Web-API控制器

public async Task<IHttpActionResult> Post(Attachment attachment)
{

我还没有在Visual Studio中测试过,但这是您需要遵循的方法

更多信息在这里:http://www.asp.net/web-api/overview/formats-and-model-binding/media-formatters

这里有个样本http://blog.marcinbudny.com/2014/02/sending-binary-data-along-with-rest-api.html .V5MDDzV7qYg