transferring data from a form with a binary image file to store in an SQL server

I am aiming to create a form where users can upload an image along with some data fields. Currently, I can only get either the image or the data fields to work separately. The following code allows me to upload an image to my SQL database as binary data. I need assistance in uploading both the data fields and the image together within the same form. Thank you in advance.

View

<form ng-submit="submitItem()" enctype='multipart/form-data'>

<input class="form-control" type="text" ng-model="itemName" placeholder="Name" />
<input class="form-control" type="text" ng-model="itemCategory" placeholder="Category" /><br />
<input class="form-control" type="text" ng-model="itemDescription" placeholder="Description..." />
<input id="fileupload" class="form-control" type="file" ng-model="imageUrl" placeholder="Image" />
<input class="form-control" type="number" ng-model="itemPrice" placeholder="Price" /><br />
<input class="btn btn-danger" type="submit" value="Add Item" />


ApiController

 public class apiItemsController : ApiController
{
    ItemInterface _adapter;
    public apiItemsController()
    {
        _adapter = new ItemDataAdapter();
    }

    public apiItemsController(ItemInterface adapter)
    {
        _adapter = adapter;
    }

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

    {
     var items = _adapter.GetItems();
        return Ok(items);
    }

    // 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();
        await Request.Content.ReadAsMultipartAsync(provider)
        .ContinueWith(async (a) =>
        {
            foreach (var file in provider.Contents)
            {
                var filename = file.Headers.ContentDisposition.FileName.Trim('\"');
                var contentType = file.Headers.ContentType.ToString();
                await file.ReadAsByteArrayAsync().ContinueWith(b =>
                {

                    item.Image = b.Result;
                });
            }
        }).Unwrap();
        new ItemDataAdapter().PostNewItem(item);
        return result;

    }

Main Controller

app.controller('MainCtrl', function ($scope, $location, $anchorScroll, $modal, $ekathuwa, $q, Item, Message, $http) {
$scope.itemArray = null;
$http.get("api/apiItems").success(function (data) {
    $scope.itemArray = data;
});
var url = "api/apiItems/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
  }).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('fileuploaded', function (e, data) {
    console.log(data);
    if (data._response.textStatus === "success") {
        for (var i = 0; i < data._response.jqXHR.responseJSON.files.length; i++) {
            ko.observable(file.name), id: ko.observable(file.id) });
        }
        $('#progress .progress-bar').css('width', '0%');
    }

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

DataAdapter

public class ItemDataAdapter : ItemInterface
{

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

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

                       .FirstOrDefault();
        return model;
    }
  public List<Item> PostNewItem( Item newItem)
    {
        ApplicationDbContext db = new ApplicationDbContext();
        db.Items.Add(newItem);
        db.SaveChanges();
        return db.Items.ToList();
    }

Class

public class Item
{
    public int ItemId { get; set; }
    public string ItemName { get; set; }
    public string ItemDescription { get; set; }
    public int ItemPrice { get; set; }
    public byte[] Image { get; set; }
    public string ItemCategory { get; set; }
    public bool Hidden { get; set; }
}

Answer №1

When implementing a file upload plugin in JavaScript, make sure to include additional form data in your options settings. There are various methods for achieving this, as detailed here.

$('#fileupload').fileupload({
    formData: {example: 'test'},
    url: url,
    dataType: 'json',
    autoUpload: true,
    maxFileSize: 5000000, // 5 MB
    disableImageResize: /Android(?!.*Chrome)|Opera/
    .test(window.navigator.userAgent),
    previewMaxWidth: 100,
    previewMaxHeight: 100,
    previewCrop: true
  })

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue with Submit Button Functionality following an Ajax Request

I am facing an issue where the submit button does not work after an ajax call, but works fine if I reload the page. The problem arises when a modal is displayed for email change confirmation. If the user confirms the change, the form submits successfully. ...

Is a referrer included in AJAX requests made from the background page of a Google Chrome Extension?

Can anyone confirm if AJAX requests sent from the background page of my Chrome Extension will include referrer information? I'm wondering about this. Appreciate any insights you can provide! ...

Unable to include checkout and clear cart buttons in popover within bootstrap 5

I am currently working with BootStrap version 5.0.0 beta-2 and facing an issue when attempting to dynamically add a button within my popover. I have ensured that the scripts are included in the following order: <script src="https://ajax.googleapis. ...

Using ng-repeat-start and ng-repeat-end in AngularJS along with nested ng-repeat

Hello, I have successfully implemented ng-repeat-start and end in a simple use case. However, I am facing an issue when trying to add an inner ng-repeat within the code snippet below: <tr ng-repeat-start="obj in rows" > <td ng-repeat="e in obj. ...

Error encountered in jQuery 3.3.1: Unable to append a row to the tbody of a table

As I attempt to dynamically insert a row into an HTML table when a click event occurs using JQuery 3.3.1 and Bootstrap 4, I encounter a slight issue. HTML: <table id='tblAddedCallsign' class='table table-striped'> </table> ...

How are the actions in react redux able to utilize dispatch and getState methods?

Could you please explain how the actions.js in the reddit example of the react redux docs is able to access the dispatch and getState functions without importing them explicitly? I was under the assumption that every method needed to be imported in each ...

Attempting to update an AJAX field with the returned value, but it only updates after clicking away from it

Image of form utilizing AJAX & JS The current setup involves a maintainer that uses AJAX to update the "Calc" field in response to a number entered in the "Order No" field. The issue is that the "Calc" field does not update immediately after typing in the ...

An object that appears to be empty at first glance, but contains values that are undefined

I am facing an issue with my object that I am populating with information. The logs show the object as empty, but when I inspect it in Chrome, it appears to have the correct details filled in. Here is a snapshot of what the logs display: closed: closed o ...

Using HTML to showcase various prompt messages based on the screen resolution

For the button click event, when clicked on desktop screens it will show a prompt message saying 'Hi'. On the other hand, when clicked on mobile screens, the prompt message displayed will be "Hello". ...

How can I ensure that the height of my dropdown menu covers the entire screen without being limited by the page height

I'm trying to adjust a dropdown menu so that it fits perfectly within the screen size, covering the entire height without showing any content beneath or below it. Currently, the menu covers the screen on some pages but scrolls and appears too large du ...

JS similar to yield*: async generator

Attempting to write a recursive async generator function, I hit a roadblock when I realized I am unsure of the syntax for yield* in the context of an async generator. In a conventional generator function, I can utilize yield* to yield all values from anot ...

Which is more efficient: filtering a JSON object or querying the database using ajax?

I am currently developing a product page that involves a selection of options that will impact the pricing of the items. The primary option allows users to choose a material, which then influences the available set of options. Within the database, there i ...

I possess 9 captivating visuals that gracefully unveil their larger counterparts upon being clicked. Curiously, this enchanting feature seems to encounter a perplexing issue within the realm of web browsing

<style type="text/javascript" src="jquery-1.11.0.min.js"></style> <style type="text/javascript" src="myCode.js"></style> </body> //jquery is within my site directory on my desktop $(document).ready(function(){ //note: $("#ar ...

Is there a way to prevent Material-UI SpeedDial from automatically closing when a SpeedDialAction button is clicked?

Looking to customize the functionality of Material-UI's SpeedDial component (https://material-ui.com/api/speed-dial/). At present, when a SpeedDialAction is clicked, the main SpeedDial component automatically closes. I want to modify this behavior s ...

Can a file be imported into Node.js without the need for packaging?

Is there a way to have an entire file evaluated in node? For example, let's say I want to evaluate the angular.js source file. An example of what the code could look like is as follows: jsdom = require("jsdom").jsdom; document = jsdom("<html>& ...

Uncover the reason behind the application's crash with Titanium

If we encounter non-crashing errors, utilizing LogCatcher can help by pinpointing which Javascript code is causing the issue. However, in the event of a crash, there's no time for logging Javascript errors. In such cases, integrating tools like ARCA ...

Can you provide guidance on the most effective approach to appending to a file using async await?

Is it safe to repeatedly call functions like fs.appendFile()? For instance, when using child_process.spawn and a "for-async-of" loop to implement tee with JavaScript. Chunked file data needs to be appended to a file while performing other processing. If ap ...

Why is my LINQ query so slow, causing timeouts, even though the generated SQL seems to be

My LINQ query is quite complex and often runs slowly, resulting in a System.Data.SqlClient.SqlException: "The wait operation timed out". However, when I log the SQL query (using a TextWriter assigned to the DataContext's Log) and run it directly on t ...

Utilizing a GET method with MongoDB

My front end has a link using axios with a placeID parameter: http://localhost:3001/api/getData?placeID=Uh8LPCRstLnJ-ZY3B41N9w I am trying to retrieve results based on the placeID in my database. I have made sure that there is data with the specific place ...

Creating a Future Prediction Graph with ECharts

I am looking to create a forecast chart that includes both Actual values (presented as a line chart) and projected values (displayed as a dotted chart). An example of what I have in mind can be seen here, created using Excel: https://i.sstatic.net/q18An.pn ...