How to upload an image using Java and store it on a server without the use of Html5

Looking to upload an image file on the server using a servlet without utilizing HTML5. While browsing through stackoverflow, most answers I found were based on PHP. I attempted to read the image file at the client-side in JavaScript with FileReader.readAsDataURL() method and then send it to the server side, decrypting it by BASE64 to create a .jpg file. However, the resulting file was unreadable by the computer. Seeking assistance to resolve this issue. Any alternative methods for uploading are welcomed. Your response should focus on JAVA JAVA JAVA. AJAX implementation is also desired. Thank you.

I've successfully uploaded an image file using a servlet, which works fine. My attempt to upload an image using AJAX by calling the same servlet through an AJAX request is failing. Utilizing common-fileupload.jar and common-io.jar in my code snippet: List items = new FileUpload(new DiskFileItemFactory()) .parseRequest(request);
This code doesn't work with AJAX as I am sending dataForm object as data.

data = new FormData();
jQuery.each($('#file')[0].files, function(i, file) {
data.append('file-'+i, file);
});

The AJAX request appears as follows:

$.ajax({
type: "POST",
data: data,
cache: false,
url: "/uploadImage/upload", 
contentType: false,    
processData: false,
success: function() {
alert("Done..!!");
}
});

Answer №1

1) To begin, create an HTML form that will allow for sending multiparty requests. You can refer to the following link for guidance on creating a form to upload files:

2) Next, set up a Java dynamic web project and incorporate a servlet into it. Here is an example to assist you with setting up your dynamic web project in Eclipse:

3) Now, create a servlet and utilize the provided code snippet for uploading files. This code utilizes the com.oreilly.servlet.MultipartRequest library.

private void uploadImage(HttpServletResponse response, HttpServletRequest request) throws IOException
{
    String dirName = request.getSession().getServletContext().getRealPath("/temp/");
    String fileName = null;
    MultipartRequest multi=null;

    try{
        multi= new MultipartRequest(request, dirName,1024*1024, "ISO-8859-1");
    } catch (IOException ex){
        ex.printStackTrace();

    }
    
    try{     
        Enumeration files = multi.getFileNames();

        while (files.hasMoreElements()){
            String name = (String) files.nextElement();
            fileName = multi.getFilesystemName(name);
        }
        
        String filePath = dirName +  System.getProperty("file.separator") + fileName;
        File clientImage = new File(filePath);

    } catch (Exception ioe){
        ioe.printStackTrace();
        logger.info("\nFile does not exist or cannot be deleted\n");
    }       
}

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

Filtering a string array in Angular based on an object's value

I am facing a challenge with two arrays in my code. The first array, $scope.termini, contains strings, and the other one, $scope.reserved, contains objects. Each object in the second array has a variable called vrijemeTermina. My goal is to filter $scope.t ...

Struggling to display the retrieved data on the webpage

Code in pages/index.js import React from 'react'; import axios from 'axios'; import ListProducts from '@/components/products/ListProducts'; const getProducts = async () => { const data = await axios.get(`${process.env.AP ...

Exploring an array using bluebird promises

I am currently facing an issue where I need to iterate over an array containing promises. My goal is to multiply all the values in the array by 2 and then return the updated array: var Bluebird = Promise.noConflict(); var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9 ...

Excessive JSON formatting is consuming an excessive amount of storage space

As I work on developing a website that recommends locations to visit in NYC, I am facing an issue with saving JSON data in local storage. My goal is to allow users to add their own suggestions and eventually integrate MongoDB into the site. To build the si ...

Stopping multiple queries in Node.js can be achieved by using proper error handling

Upon verifying the existence of the name, the program continues to the subsequent query and proceeds with inserting data, which results in an error due to multiple responses being sent. How can I modify it to halt execution after checking if (results.row ...

How can you set a predetermined value for a dropdown menu after populating it with data from a Django database?

I currently have a query in my Views.py file that is used to populate a dropdown menu. The query works properly, but I need it to display a specific value that is stored in a variable based on the user's selection. For example, let's suppose we ...

The word-break CSS property is ineffective in this situation

I've been experimenting with the word-break css property, but I just can't seem to get it to work even when using a simple example. Here's my code: React: render() { return ( <h5 className="word-break">A very very long line.... ...

Refresh Grid or Repeater After Upload Using AjaxFileUpload UploadComplete Event in ASP.NET

Is there a way to refresh the data in a GridView or Repeater after an AjaxFileUpload UploadComplete event? I want to be able to upload multiple pictures using AjaxFileUpload and have them displayed in a GridView or Repeater control once they are uploaded. ...

One-page application featuring preloaded data from a backend API

Imagine building a single-page application that relies heavily on client-side interactions communicating with the server through API methods. When we land on the index page that displays all records from the database, we essentially make two initial requ ...

The Typescript const assertion translated into Javascript

Is there a way in JavaScript to achieve constant-like behavior similar to TypeScript's const assertion? const arr = [1,2,3,4] as const I am looking for a solution in JavaScript that allows me to create an array that cannot be further mutated. ...

The tab key seems to be malfunctioning when triggered during a jquery change event

I encountered an unusual issue with my jQuery events, and I'm not entirely sure if it's a problem related to jQuery. In hopes that some jQuery experts can shed some light on this. The code snippet below was included in my HTML page to automatica ...

Confirming the user's login status using AJAX on the front-end

Currently facing the following issue: I am working on a Rails (version 3.2.8) application that utilizes devise for authentication. The backend is a RESTful API while the front-end consists of a backbone one-page app. Although I have successfully implemen ...

Vue3 is struggling to apply dynamic styling exclusively to certain buttons

Currently, I am diving into the world of vue and facing a challenge in styling buttons dynamically when clicked individually. These buttons serve as filters for a list of products, and my goal is to apply one style when the filter is 'on' and ano ...

Notification continuously appears when clicking outside of Chrome

I have implemented the use of onblur on a text box to display an alert. However, I encountered an issue where if I click outside my Chrome browser after entering text in the text box and then click on the Chrome browser button in the task bar, the alert ap ...

Creating dynamic images in JavaScript by assigning URL paths from string variables

Currently, I am utilizing JavaScript to parse through an XML file. One interesting aspect of the XML is that it contains URLs which link to images like this one: http://localhost/pic.jpg Throughout the parsing process, I am storing each URL as a string va ...

Using finally() to correctly construct a Javascript promise

Currently, I am working on an Express API that utilizes the mssql package. If I neglect to execute sql.close(), an error is triggered displaying: Error: Global connection already exists. Call sql.close() first. I aim to keep the endpoints simple and e ...

Localhost file not refreshing

I'm feeling quite frustrated at the moment. It seems like such a simple issue, but I can't seem to figure it out. I have created a basic webpage with a "tree-view" structure. In my readjson.js file, I am reading from a json file located in json/ ...

What are the steps to view my HTML webpage on a smartphone?

Recently, I successfully created an HTML webpage with CSS and JS that looks and functions perfectly on my PC. However, when attempting to access it on my phone, I encountered some issues. Despite transferring all the necessary files to my phone, only the ...

Achieving camera zoom in threeJS without the use of trackball controls or any other camera control libraries

Currently, I'm utilizing threeJS to manipulate a camera within my scene. The camera is configured to orbit in a circular motion around an object when the left and right keys are pressed on the keyboard. However, I am seeking guidance on how to impleme ...

Internet Explorer encounters a "no element found" error while using Selenium WebDriver

Encountering the error below in Internet Explorer 8, but it works fine in Firefox (Both have the same name and xpath) "Unable to find element with name == username (WARNING: The server did not provide any stacktrace information)" This is how my HTML appe ...