2

I have a MVC webapi project that uses the jquery file upload plugin to send and convert a jpg to a binary image with data fields to my sql server. that is working just fine. I need help retrieving the form data and converting the image back to a jpg to display all the form data in the view. it started as a angular project but the solution i found to upload was with jquery. i have not been able to find examples that convert both the binary image with the data fields. any help is appreciated

Api Controller

 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;

    }

Data Adapter

 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;
    }

Main Controller

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-File Upload

 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');

View

<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>

Submit Form View

<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>
4
  • github.com/blueimp/jQuery-File-Upload has an angular directive built in that does what you need... Commented Apr 11, 2014 at 0:47
  • i cant find any information on retrieving the files from the API? Commented Apr 11, 2014 at 3:52
  • Do you mean how do you access it once uploaded? I think the issue is you have way too much code and its hard to develop a solution for you that is simple. I started doing one but its unclear what you really need from this post. Commented Apr 11, 2014 at 10:16
  • yes, i have the get call working but i can not convert the binary image back into jpeg while it has the other data fields along with it. i wasnt sure how much code was needed. Commented Apr 11, 2014 at 16:18

1 Answer 1

1

found the solution

<img class="img-responsive" ng-alt="" src="{{'data:image/jpg;base64,'+item.Image}}"/>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.