What is the process for uploading a file selected with the Dojo Uploader to a servlet using Dojo version 1.7.5?

I've been struggling to find a proper method for posting a file selected using dojox.form.Uploader to my servlet. Unfortunately, there is limited documentation available for Dojo and not many examples, demos, or tutorials to follow. Any help with this would be greatly appreciated.

Here is the code snippet in JSP:

<tr>
    <td colspan="9"><h2>File Upload<br /></h2><h3>To add 800#s using a file</h3></td>
</tr>
<tr>
    <td colspan="9"><input type="file" data-dojo-type="dojox.form.Uploader" label ="Browse" multiple="false" id="uploader" onchange="check();" uploadOnSelect="true" url="/MyProject/app/ActionRequestHandlerServlet"/>
        <div id="files" data-dojo-type="dojox.form.uploader.FileList" uploaderId="uploader" ></div>
    </td>
</tr>`

Below is the JavaScript code that is used:

function check() {
    alert(dijit.byId("uploader").value);
    formPostObject.file = dijit.byId("uploader").value;
    sendFile();
}

function sendFile() {
    dojo.io.iframe.send({
        url: "/MyProject/app/ActionRequestHandlerServlet", // Replace with yours
        method: "post",
        handleAs: "text",
        form: dojo.byId("uploader"),
        load: function(response, ioArgs) {
            console.log("Upload OK", response, ioArgs);
            return response;
        },
        error: function(response, ioArgs) {
            console.log("Upload FAILED!!!", response, ioArgs);
            return response;
        }
    });
}

Despite implementing the above code, I am not getting any response. The sysout statements in my servlet are also not being printed. Additionally, I'm encountering a JavaScript error in dojo.js -> 'length' is null or not an object, even though I'm not using 'length' anywhere in my code.

If anyone could provide assistance, it would be greatly appreciated. Thank you in advance.

Answer №1

Here is the setup that worked for me with Dojo 1.6, but it should work the same in 1.7. The key factor is that using enctype="multipart/form-data" requires Servlet 3.0 functionality to function properly. Additionally, the servlet requires the @MultipartConfig annotation to be added.

--- HTML --

dojo.require("dojox.form.Uploader");
dojo.require("dojox.form.uploader.FileList");
dojo.require("dojox.embed.Flash");
if(dojox.embed.Flash.available){
  dojo.require("dojox.form.uploader.plugins.Flash");
}else{
  dojo.require("dojox.form.uploader.plugins.IFrame");
}
</script>

<body>
<form method="post" action="ReadInputFilesServlet" id="myForm"
               enctype="multipart/form-data" >
 <fieldset>
    <input name="uploadedfile" multiple="true" type="file" id="uploader"
      dojoType="dojox.form.Uploader" label="Select Some Files" >
       <input type="submit" label="Submit" dojoType="dijit.form.Button" />
    <div id="files" dojoType="dojox.form.uploader.FileList"
                    uploaderId="uploader"></div>
 </fieldset>
</form>

--- in servlet --

@MultipartConfig(location="C:\\TMP_FILES", fileSizeThreshold=1024*1024, maxFileSize=1024*1024*5, maxRequestSize=1024*1024*5*5)

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub

        Collection <Part> files = request.getParts();
        Iterator <Part> iter = files.iterator();
        while(iter.hasNext()){
            Part part = iter.next();

            String filename = getFileName(part);

            System.out.println("File "+ filename);

            BufferedReader rd = new BufferedReader(new              InputStreamReader(part.getInputStream()));
            String line;
            while ((line = rd.readLine()) != null) {
            System.out.println(line);
            }
            rd.close();
        }

    }

public static String getFileName(Part filePart)
{
    String header = filePart.getHeader("content-disposition");
    for(String headerPart : header.split(";"))
    {
        if(headerPart.trim().startsWith("filename"))
        {
            return headerPart.substring(headerPart.indexOf('=') + 1).trim()
                             .replace("\"", "");
        }
    }
    return null;
}

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

update-post-thumbnail wp-ajax return false

I have been attempting to utilize the media manager within Wordpress. I am using the post editor outside of the admin area, allowing users to create posts with a featured image. I have used the _wp_post_thumbnail_html function to display the image or provi ...

Ways to insert a line break within a jQuery function using text()

I am looking to add a new line in my jQuery function. $.ajax({ url:"http: //192.168.1.4/Experiements/webservices/api.php", type:"GET", dataType:"json", data:{type:"login", UserName:userId,Password:userPassword}, ...

Creating synchronous behavior using promises in Javascript

Currently, I am working with Ionic2/Typescript and facing an issue regarding synchronization of two Promises. I need both Promises to complete before proceeding further in a synchronous manner. To achieve this, I have placed the calls to these functions in ...

What is the limit on the amount of input data (in CSV or JSON format) that can be used to create a

Attempting to visualize a large dataset using D3.js has posed a challenge for me. The data size is 261 MB with approximately 400,000 rows in CSV format. Even when I attempt to run it with just 100,000 rows, the visualization does not appear on the browser. ...

Refresh jQuery DataTable with updated search results

I have a function that loads the DataTable once the document is loaded. $(document).ready(function() { var $dataTable = $('#example1').DataTable({ "ajax": 'api/qnams_all.php', "dataType": "json", "bDestroy": true, "s ...

Struggling to locate __proto__ of the global object known as "window."

Currently I am using Google Chrome browser. console.log(window.__proto__.__proto__.__proto__); console.log(window.__proto__.__proto__.__proto__ === EventTarget.prototype); The first code mentioned above returns EventTarget.prototype for me. This can be ...

How does Socket.io facilitate a basic web socket connection with a specific URL?

My current project involves a client making a WebSocket request to the following URL: ws://localhost:3000/feed/XBTMUR https://i.sstatic.net/R7H9T.png On my server side, I am utilizing NodeJs with express running. I have decided to implement Socket.io in ...

An unexpected issue occurred: Unable to invoke method on NPObject

I am new to JSON and having trouble accessing object data. Here is the code snippet: <!doctype html> <html> <head> <meta charset="utf-8"> <title>ajax </title> </head> <body> <p id="p"></p& ...

Click on a div element to activate and set a PHP session variable

I am in the process of creating a setup where if a user clicks on a specific div element, a PHP session variable should be assigned the value of another session variable that has been previously defined. For instance, when the user clicks on the div with a ...

No data returned from API call in Next.js and Strapi

Recently, I encountered an issue with my Next.js frontend application that fetches data from a Strapi backend. Despite seeing requests being made in the Strapi developer logs, the retrieved data is empty. Below is a snippet of my Next.js code: import { us ...

Exploring ways to reach a specific digit level in JavaScript

As a newcomer to JavaScript, I've been searching online and trying different solutions but none have worked for me. Currently, I have a variable called num = 71.666666666 I'm looking to limit this number to 71.66 So far, I have attempted the f ...

Managing the inclusion of double quotes that are dynamically inserted using ajax and jquery

In this particular code snippet, the values of two input fields are being sent to another service via API. Everything functions as expected unless one of the input values contains a double quote ", which causes the API to return a 400 error (bad request) u ...

What's causing the show/hide feature to malfunction within the for loop in Vue.js?

I've encountered an issue with my for loop where the show/hide functionality doesn't seem to work despite everything else functioning properly. I've been trying to troubleshoot this problem without success. <div id="app"> <ul> ...

What is the best way to display a loading image and temporarily disable a button for 3 seconds before initiating the process of sending post data from another page via

Is there a way to display a loading image and disable a button for 3 seconds before sending post data from another page using AJAX POST? Once the OK button is clicked, I would like the loading image to appear and the <input type="button" value="Check" ...

.malfunctioning in Internet Explorer due to compatibility issues

While I have not personally experienced this issue, there seems to be a problem with a form on our website. After changing the value (using .change()), the field is supposed to update by sending data to save.php. However, some users have reported that this ...

What might be causing the issue with my ajax request to the PHP file within the data parameter?

Although I am successfully getting my php value into a JavaScript variable, it seems like my script.js file is unable to find it. For the sake of brevity, some files have been omitted in this question. The main issue is that the script.js file retrieves th ...

Retrieve a dynamic HTML object ID using jQuery within Angular

In my Angular application, I have implemented three accordions on a single page. Each accordion loads a component view containing a dynamically generated table. As a result, there are three tables displayed on the page - one for each accordion section. Abo ...

Making an Http Get request in Angular 2 by passing a JSON object

How can I make an HTTP GET request and send a JSON object along with it? Here is the JSON object: {{firstname:"Peter", lastname:"Test"} I want to pass this object in the HTTP request to receive a list of matched persons. Is this possible? The example o ...

Is there a way to output several lines from a JSON file in print form?

I'm working with HTML code that displays multiple lines from a JSON file, but it only shows one line at a time. How can I modify the code to display all users' information? <!DOCTYPE html> <html> <head> <script> function ...

The response from the Whatsapp-web-js API can be delayed

As I work on creating an API to retrieve groupChat IDs using the express framework and whatsapp-web-js library, I've encountered an issue. The initial request to the endpoint after starting the server yields a response within 31 seconds, but subsequen ...