检索包含二进制图像的表单数据,并使用web api在视图中显示

时间:2014-04-11 00:08:26

标签: jquery sql angularjs asp.net-web-api filestream

我有一个MVC webapi项目,它使用jquery文件上传插件将jpg发送并转换为带有数据字段的二进制映像到我的sql server。这工作得很好。我需要帮助检索表单数据并将图像转换回jpg以显示视图中的所有表单数据。它起初是一个角度项目,但我发现上传的解决方案是jquery。我无法找到将二进制图像与数据字段一起转换的示例。任何帮助表示赞赏

Api控制器

 public apiItemController(ITexasIceAdapter adapter)
    {
        _adapter = adapter;
    }

    //// GET api/<controller>
    public IHttpActionResult Get()
    {

        var item = _adapter.GetItems();
        return Ok(item);
    }

    // GET api/<controller>/5
    public IHttpActionResult Get(int id)
    {
        Item item = new Item();
        item = _adapter.GetItem(id);
        if (item == null)
        {
            return NotFound();
        }
        return Ok(item);
    }



    //POST
     public async Task<object> PostFile()
    {
        if (!Request.Content.IsMimeMultipartContent())
           throw new Exception();


        var provider = new MultipartMemoryStreamProvider();
        var result = new { files = new List<object>() };
        var item = new Item();

        item.ItemName = HttpContext.Current.Request.Form["itemName"];
        item.ItemDescription = HttpContext.Current.Request.Form["itemDescription"];
        item.ItemCategory = HttpContext.Current.Request.Form["itemCategory"];
        item.ItemPrice = HttpContext.Current.Request.Form["itemPrice"];
        await Request.Content.ReadAsMultipartAsync(provider)
         .ContinueWith(async (a) =>
         {
             foreach (var file in provider.Contents)
             {
                 if (file.Headers.ContentLength > 1000)
                 {
                     var filename = file.Headers.ContentDisposition.FileName.Trim('\"');
                     var contentType = file.Headers.ContentType.ToString();
                     await file.ReadAsByteArrayAsync().ContinueWith(b => { item.Image = b.Result; });
                 }


             }


         }).Unwrap();
        new TexasIceDataAdapter().PostNewItem(item);
        return result;

    }

数据适配器

 public List<Item> PostNewItem(Item newItem)
    {
        db.Items.Add(newItem);
        db.SaveChanges();

        return db.Items.ToList();
    }


    public List<Item> GetItems()
    {
        List<Item> items = new List<Item>();
        items = db.Items.ToList();
        return items;
    }


    public Item GetItem(int id)
    {
        Item model = new Item();
        model = db.Items.Where(j => j.ItemId == id)

                       .FirstOrDefault();
        return model;
    }

主控制器

app.controller('MainCtrl', function ($scope, $location, $anchorScroll, $ekathuwa, $q, $http) {
$http({
    method: "GET",
    url: "/api/apiItem/",

}).success(function (data, status) {
    $scope.itemArray = data;
    console.log(data);

});

Jquery Ui-文件上传

 var url = "/api/apiItem/File",
uploadButton = $('<button/>')
.addClass('btn btn-primary')
.prop('disabled', true)
.text('Processing...')
.on('click', function () {
    var $this = $(this),
    data = $this.data();
    $this.off('click').text('Abort').on('click', function () {
        $this.remove();
        data.abort();
    });
    data.submit().always(function () {
        $this.remove();
    });
});

$('#fileupload').fileupload({
    url: url,
    dataType: 'json',
    autoUpload: true,

    maxFileSize: 5000000, // 5 MB
    disableImageResize: /Android(?!.*Chrome)|Opera/
    .test(window.navigator.userAgent),
    previewMaxWidth: 100,
    previewMaxHeight: 100,
    previewCrop: true
     , submit: function (e, data) {
         // The example input, doesn't have to be part of the upload form:
         var itemName = $('#itemName');
         var itemDescription = $('#itemDescription');
         var itemCategory = $('#itemCategory');
         var itemPrice = $('#itemPrice');
         data.formData = {};
         data.formData.itemName = itemName.val();

         data.formData.itemDescription = itemDescription.val();
         data.formData.itemCategory = itemCategory.val();
         data.formData.itemPrice = itemPrice.val();
     }
}).on('fileuploadadd', function (e, data) {

    data.context = $('<div/>').appendTo('#files');
    $.each(data.files, function (index, file) {
        var node = $('<p/>')
        .append($('<span/>').text(file.name));
        if (!index) {
            node
            .append('<br>')
            .append(uploadButton.clone(true).data(data));
        }
        node.appendTo(data.context);
    });
}).on('fileuploadprocessalways', function (e, data) {
    var index = data.index,
    file = data.files[index],
    node = $(data.context.children()[index]);
    if (file.preview) {
        node.prepend('<br>').prepend(file.preview);
    }
    if (file.error) {
        node.append('<br>').append($('<span class="text-danger"/>').text(file.error));
    }
    if (index + 1 === data.files.length) {
        data.context.find('button').text('Upload').prop('disabled', !!data.files.error);
    }
}).on('fileuploadprogressall', function (e, data) {
    var progress = parseInt(data.loaded / data.total * 100, 10);
    $('#progress .progress-bar').css('width', progress + '%');
}).on('fileuploaddone', function (e, data) {
    $.each(data.result.files, function (index, file) {
        if (file.url) {
            var link = $('<a>').attr('target', '_blank').prop('href', file.url);
            $(data.context.children()[index]).wrap(link);
        } else if (file.error) {
            var error = $('<span class="text-danger"/>').text(file.error);
            $(data.context.children()[index]).append('<br>').append(error);
        }
    });
}).on('fileuploadfail', function (e, data) {
    $.each(data.files, function (index, file) {
        var error = $('<span class="text-danger"/>').text('File upload failed.');
        $(data.context.children()[index]).append('<br>').append(error);
    });
}).bind('fileuploadalways', function (e, data) {
    console.log(data);
    if (data._response.textStatus === "success") {
        for (var i = 0; i < data._response.jqXHR.responseJSON.files.length; i++) {

        }
        $('#progress .progress-bar').css('width', '0%');
    }

}).prop('disabled', !$.support.fileInput)
          .parent().addClass($.support.fileInput ? undefined : 'disabled');

查看

<table class="table table-hover">
<tr>
    <th>Category</th>
    <th>Name</th>
    <th>Description</th>
    <th>Price</th>

</tr>
<tr ng-repeat="item in itemArray | filter:{ItemCategory:ItemItemCategory}" style="font-size:18px;">
    <td src="{{item.Image}}" class="img-responsive" ng-click="open(photo)">{{item.Image}}</td>
    <td><a data-toggle="modal" data-target=".bs-example-modal-lg">{{item.Image}}</a> </td>
    <td style="color: #3953a5; width: 100px;"><strong>{{item.ItemCategory}}</strong></td>
    <td style="width: 100px;"><strong>{{item.ItemName}}</strong></td>
    <td style="width:640px;">{{item.ItemDescription}}</td>
    <td>$ {{item.ItemPrice}}</td>

</tr>

提交表单视图

<form class="form-horizontal" id="fileupload" enctype="multipart/form-data">
            <fieldset>
                <!-- Text input-->
                <div class="form-group">
                    <label class="col-md-2 control-label">Name :</label>
                    <div class="col-md-8">
                        <input id="itemName" type="text" class="form-control input-md">

                    </div>
                </div>

                <!-- Textarea -->
                <div class="form-group">
                    <label class="col-md-2 control-label">Description :</label>
                    <div class="col-md-8">
                        <input class="form-control" type="text" id="itemDescription">
                    </div>
                </div>
                <!-- Textarea -->
                <div class="form-group">
                    <label class="col-md-2 control-label">Category :</label>
                    <div class="col-md-8">
                        <input class="form-control" type="text" id="itemCategory" />
                    </div>
                </div>
                <!-- Textarea -->
                <div class="form-group">
                    <label class="col-md-2 control-label">Price :</label>
                    <div class="col-md-8">
                        <input class="form-control" type="text" id="itemPrice" />
                    </div>
                </div>
                <!-- Textarea -->
                <div class="form-group">
                    <label class="col-md-2 control-label">File :</label>
                    <div class="col-md-8">
                        <input type="file"  name="Image" />
                    </div>
                </div>


                <!-- Button -->
                <div class="form-group">
                    <label class="col-md-2 control-label" for="send"></label>
                    <div class="col-md-8">
                        <button type="submit" class="btn btn-primary">Send</button>
                    </div>
                </div>

            </fieldset>
        </form>

1 个答案:

答案 0 :(得分:1)

找到解决方案

<img class="img-responsive" ng-alt="" src="{{'data:image/jpg;base64,'+item.Image}}"/>