Implementing Dropzone in an Angular MVC5 project

For more information about dropzone, visit this link

I am currently implementing dropzone as my file upload handler with the combination of angularjs and MVC5.

The challenge I'm facing is getting the Http post request to go from the angularjs service to the MVC 5 backend successfully.

My goal is to send not only the files but also other values such as action and a string value named "values".

Check out the code below (in the angularjs service):

sendProductFiles: function (act, file, val) {
        return $http.post('/attributes/uploads', $.param({
            action: act,
            files: file,
            values: val
        }), 
        {
            transformRequest: angular.identity,
            headers: {
                'Content-Type': undefined
            }
        })
    }

In the controller (angular):

$scope.intakeUpload = function (files) {
    var fd = new FormData();
    for (var i = 0; i < files.length; i++)
        fd.append('file', files[i]);


    AttributionViewService.sendProductFiles("addAttr", fd, $scope.selectedValues).then(function (res) {

    }, function (err) {

    });
}
Dropzone.options.myAwesomeDropzone = {

    autoProcessQueue: false,
    uploadMultiple: true,
    parallelUploads: 100,
    maxFiles: 100,

    // Dropzone settings
    init: function () {
        var myDropzone = this;

        this.element.querySelector("button[type=submit]").addEventListener("click", function (e) {
            e.preventDefault();
            e.stopPropagation();
            myDropzone.processQueue();
        });
        this.on("sendingmultiple", function (files) {
            $scope.intakeUpload(files);
        });
        this.on("addedfile", function (file) {
            file.previewElement.addEventListener("click", function () { this.removeFile(file); });
        });
    }

}

In the MVC 5 controller:

[HttpPost]
    [Route("attributes/uploads")]
    public ActionResult AcceptUploads(string action, HttpPostedFile[] files, string values)
    {
        if (files.Length <= 0)
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        foreach (var file in files)
        {
            System.Diagnostics.Debug.WriteLine(file.FileName);
        }
        System.Diagnostics.Debug.WriteLine(values); 
        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
    }

Currently, I am encountering a jQuery error that states Uncaught TypeError: Illegal invocation.

Additionally, I have attempted the following:

Angular Service:

 sendProductFiles: function (act, file, val) {
        return $http.post('/attributes/uploads', $.param({
            action: act,
            files: file,
            values: val
        }), {
            headers: {
                'Content-Type': 'multipart/form-data'
            }
        })

Answer №1

Issue Resolved!

 $scope.uploadIntake = function (files) {
    var fd = new FormData();
    for (var i = 0; i < files.length; i++)
        fd.append('files', files[i]);

    fd.append("action", "addAttr");
    fd.append("values", $scope.selectedValues);
    AttributionViewService.sendProductFiles(fd).then(function (res) {

    }, function (err) {

    });
}


 [HttpPost]
    [Route("attributes/uploads")]
    public ActionResult HandleUploads(string action, IEnumerable<HttpPostedFileBase> files, string values)
    {
        if (files.Count() <= 0)
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        foreach (var file in files) 
        {
            System.Diagnostics.Debug.WriteLine(file.FileName);
        }
        System.Diagnostics.Debug.WriteLine(values); 
        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
    }

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

Can you explain the meaning of assigning `function() {}` to a variable?

I understand that functions are considered objects in javascript and can be assigned to variables. I've come across this question as well: How does the (function() {})() construct work and why do people use it?. However, I'm curious about what e ...

Encountered difficulties while attempting to use keyboard input and received a null value when attempting to retrieve a data-* attribute using Python and Selenium

Encountered an issue with keyboard interaction and finding a null value for the data-* attribute during automated login attempts on Gmail using Python and Selenium While attempting to automatically log in to Gmail using Python and Selenium, I successfully ...

Every time I hover, my jQuery code keeps repeating the hover effect

I am currently facing an issue that has me stumped on finding a solution. The problem arises when I hover over the .div multiple times, the animation just doesn't stop and keeps running continuously. What I aim for is to have the .hidden element fad ...

Ajax: Why am I receiving an error response instead of a successful one?

It's puzzling why my code is triggering the error function instead of success. The console.log keeps showing me this: Object {readyState: 0, getResponseHeader: function, getAllResponseHeaders: function, setRequestHeader: function, overrideMimeType: f ...

Having trouble with filtering the Date field in ngTable within an angularjs project

Currently tackling an issue with the date field filter in an angularjs ngTable project. Specifically, when typing '2018' into the filter, no results are being displayed on the table. I attempted to filter the date field as text using filter="{ or ...

Alter the properties based on the size of the window

I am working with React-Spring and I need to adjust the offset of a component when the window size changes. I attempted the following solution, but it is not functioning correctly and requires me to refresh the browser each time. <ParallaxLayer ...

The interaction between AngularJS ui-router and OAuth2 access_tokens causes conflicts

I have a front-end built using AngularJS with ui-router. In order to interact with the REST API on the backend, I need to obtain an OAuth2 access token through implicit grant. The issue arises during the final step of the OAuth process, when the access to ...

Tips for utilizing the selected option in the name attribute with Javascript or jQuery

I am looking to use the "selected" attribute in the option element based on the name attribute using JavaScript or jQuery. Essentially, I want the option with name="1" to be automatically selected when the page loads. I have attempted the following code, b ...

Tips for modifying environment variables for development and production stages

I am looking to deploy a React app along with a Node server on Heroku. It seems that using create-react-app should allow me to determine if I'm in development or production by using process.env.NODE_ENV. However, I always seem to get "development" ev ...

How can I make a polygon or polyhedron using Three.js?

Is it possible to generate polygon or polyhedron shapes in three.js using alternative methods? var customShapePts = []; customShapePts.push( new THREE.Vector2 ( -50, 200 ) ); customShapePts.push( new THREE.Vector2 ( 100, 200 ) ); customShapePts.push( ne ...

Acquire dynamically loaded HTML content using Ajax within a WebView on an Android

I have been attempting to extract the content of a web page on an Android platform. Despite trying JSoup, I faced a limitation with ajax support. As an alternative, I am endeavoring to embed the URL within a hidden web view and retrieve the HTML in the on ...

Exploring OOP Strategies within the Angular MVC Framework!

After coming across a question on Stack Overflow that was similar to mine, I realized I have a lot to learn about Object-Oriented Programming (OOP). Up until now, my coding experience has been mainly procedural. Before diving into my question, let me provi ...

in AngularJS, check for object attributes existence before proceeding to use them

Currently, I have a filter function that is designed to check the latitude and longitude distance of objects within an array against the range selected by the user. However, there is a problem in which some objects within the array do not possess latitude ...

Media queries in CSS appear to be dysfunctional when used on Microsoft Edge

@media (min-width: 992px) and (max-width: 1140px) { .mr-1024-none { margin-right: 0px !important; } .mt-1024 { margin-top: 1rem !important; } .d-1024-none { display: none !important; } } Utilizing the ...

Utilize the power of Javascript/AJAX or jQuery to submit multiple forms simultaneously

I am currently working on a project which involves having 3 forms on a single page. The reason behind this is that one of the forms is displayed in a modal dialog. My goal is to allow users to submit all 3 forms with a single button click, and I also wan ...

Navigation guard error: Caught in an infinite redirect loop

I have set up a new vue3 router and configured different routes: const routes = [ { path: "/", name: "home", component: HomeView, }, { path: "/about", name: "about", component: () => ...

Showing JSON information in an Angular application

Upon page load, I am encountering an issue with retrieving and storing JSON data objects in Angular scope for use on my page and in my controller. When attempting to access the value, I receive the error message: angular.js:11655 ReferenceError: data is ...

Tips for automatically loading a new page or URL when a user scrolls to the bottom

I am working on implementing infinite scroll functionality, where a new page loads automatically when the user reaches the bottom of the page or a particular div. Currently, I have this code that loads a new page onclick. $("#about").click(function(){ ...

Is it possible to selectively export certain interfaces within a .d.ts file?

// configuration.d.ts export interface Configuration { MENU_STRUCTURE: Node[]; } interface Node { name: string; } Looking at the snippet above, I am aiming to only export Configuration. However, I noticed that I can also import Node from an ext ...

Using Angular.JS to iterate over a nested JSON array using ng-repeat

I am currently working on a People service that utilizes $resource. I make a call to this service from a PeopleCtrl using People.query() in order to retrieve a list of users from a json api. The returned data looks like this: [ { "usr_id" : "1" ...