Having trouble with a CSS selector within a JSP page when attempting to dynamically set the background of a div

Currently, I am in the process of developing an image uploader feature that will enable users to upload images and set them as backgrounds for a div element. Specifically, the .mm11 class represents a post-it style card that initially does not have a background image but includes buttons for choosing and uploading files.

I have successfully managed to upload the images to a folder within my tomcat directory and display them using the following code:

<img src='uploads/<%=fileName%>' />

However, setting the uploaded picture as the background has proven to be challenging. I would greatly appreciate any guidance on this matter, as I have been grappling with it for quite some time now.

<div id="uploadsContainer" class="mm11Container" style="top:100px; left: 100px;">
            <div id="g" class="mm11 card front face">
                <form action="

                    <%@ page import="java.io.*,java.util.*, javax.servlet.*" %>
                    <%@ page import="javax.servlet.http.*" %>
                    <%@ page import="org.apache.commons.fileupload.*" %>
                    <%@ page import="org.apache.commons.fileupload.disk.*" %>
                    <%@ page import="org.apache.commons.fileupload.servlet.*" %>
                    <%@ page import="org.apache.commons.io.output.*" %>

                    <%
                    File file ;
                    String fileName = "";
                    int maxFileSize = 5000 * 1024;
                    int maxMemSize = 5000 * 1024;
                    ServletContext context = pageContext.getServletContext();
                    String filePath = context.getInitParameter("file-upload");

                    // Verify the content type
                    String contentType = request.getContentType();

                    DiskFileItemFactory factory = new DiskFileItemFactory();
                    factory.setSizeThreshold(maxMemSize);
                    
                   
                    factory.setRepository(new File("uploads/"));

                   
                    ServletFileUpload upload = new ServletFileUpload(factory);
                    upload.setHeaderEncoding("ISO-8858-2");

                   
                    upload.setSizeMax( maxFileSize );
                    try {
                    
                    List fileItems = upload.parseRequest(request);

                    
                    Iterator iter = fileItems.iterator();

                        while ( iter.hasNext () ) {
                        FileItem fi = (FileItem)iter.next();
                        
                        if ( !fi.isFormField () ) {
                           
                            String fieldName = fi.getFieldName();
                            fileName = fi.getName();
                            
                            if( fileName.lastIndexOf("\\") >= 0 ){
                            file = new File( filePath + fileName.substring( fileName.lastIndexOf("\\"))) ;
                        }
                        else {
                            file = new File( filePath + fileName.substring(fileName.lastIndexOf("\\")+1)) ;
                        }
                        fi.write( file ) ;
                        }
                    }
                } catch(Exception ex) {
                    System.out.println(ex);
                }

                %>"
                    method="post" enctype="multipart/form-data">
                    <input class="uploads" type="file" name="file" size="50"/>
                    <input class="uploadFile" type="submit" value="Upload File"/>
                    <script type="text/javascript">
                     
                        $('.mm11').css('background-image', 'uploads/<%=fileName%>');
                        alert("here filename = "+'uploads/<%=fileName%>');
                    </script>
                    
                </form>
            </div>
        </div>

Another attempt involved using AJAX by replacing the script tags with the following code:

var ajx=new XMLHttpRequest();


ajx.onreadystatechange=function()
{
  if (ajx.readyState==4 &amp;&amp; ajx.status==200)
  {
     $("#g").css('background-image', 'uploads/<%=fileName%>');
  }
}
ajx.open("GET","index.jsp",true);
ajx.send();

Unfortunately, this approach did not yield the desired results. To verify that I can access the div element correctly, I tested it by adding the following line of code:

$("#g").empty().css('background-image', 'uploads/<%=fileName%>');

Surprisingly, this command cleared the div, showcasing that the system recognizes the element. So why isn't the background image being set?

Additionally, there seems to be a related issue where including the line:

if (contentType.indexOf("multipart/form-data") >= 0) 

(which is currently commented out) causes an alert to appear when visiting the page for the first time with the fileName set to the last uploaded file. However, when included, it leads to a Null Pointer Exception due to contentType being null. Any insights into this matter would be much appreciated.

Answer №1

Your input:

background-image', 'uploads/<%=fileName%>'

Recommended code:

background-image:url("uploads/<%=fileName%");

This variation may be more suitable.

Trust this aids you.

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

The first parameter in Vue router is optional

Is there a way to make the first parameter in my list of routes optional? I want the parameter to change a header in my api calls if it's present in the url, but everything else should stay the same. Instead of creating two sets of routes to handle t ...

Clicking on a class within a single tag can be selected using

Currently facing a seemingly trivial issue that I can't quite figure out. I have a jQuery function that selects the class of a tag when clicked, but the problem is that it also selects every other tag beneath the clicked tag in structural order. Howev ...

How come my div doesn't stick together with the other div while moving?

I am trying to figure out how to make the blue "shield" div cover the red "button" div after 3 clicks successfully. It seems like no matter what I do, the positioning is always off. I've played around with the randomplace variable, but nothing seems t ...

Navigate through the JSON object and generate all possible combinations of nested elements

Here is a JSON object that I need to iterate through in order to generate all possible nested group names: { "groups": [ { "group": "group1", "childrens": [ { "group": "group1_1", ...

Ajax - Every single request has been successfully fulfilled

I am struggling to determine when all my Ajax requests are finished in order to call another function. I have attempted to use various methods with native Ajax functions in Chrome, but none of them seem to be working for me. Can someone please help me? H ...

Prevent parent element from triggering double click when double clicking on children element with CSS or jQuery

Check out my project demo here Whenever I double click on a child element, it also triggers the parent element at the same time. I want to prevent this behavior so that only the child element is affected by the double click event. Can anyone provide assis ...

How can data be submitted to an Asp.net page method?

Here's a question about what happens 'behind the scenes': I'm sending data from jQuery AJAX to an ASP.NET page method. (the method name is Show1) When using Fiddler, it shows: POST http://localhost:54517/WebSite8/Default.aspx/Show1 H ...

Transferring data from an Express server to a React frontend perspective

I am relatively new to working with the MERN stack, so please forgive me if this question sounds novice. I am currently developing an application that is designed to visit a specific URL, extract some text data from it, and then display this information on ...

Sound did not play when certain pictures made contact with other pictures

English is not my native language and I am a beginner in programming. I know my explanation may not be perfect, but I'm trying my best to communicate my ideas clearly. Please be patient with me and offer constructive feedback instead of downvoting, as ...

Having difficulty implementing pagination functionality when web scraping using NodeJS

Currently, I am creating a script that scrapes data from public directories and saves it to a CSV file. However, I am encountering difficulties when trying to automate the pagination process. The source code I am using includes: const rp = require(' ...

Understanding how to extract inner text and splitting it can be a challenging task for developers when working with Javascript

Exploring the following basic html code: <div id="content"> This is a test </div> I am puzzled as to why this works: $(function(){ text = 'this is a text'; word = text.split(' '); alert(word[1]) }) while this does not: ...

Error message: "Missing attribute X in the GraphQL result for Vue"

Recently started using vue as a frontend with vue 2.3.11 and Django 3 as the backend, connecting them through Apollo via vue-cli. In my backend, I have a table named documents which consists of only a name and an id field. I am fetching this data from the ...

Combining two divs to share the same linear gradient and shadow effect

Greetings to all our valued partners! I am seeking guidance on how to achieve the following task for a web application I am developing: Within my webapp, I have designed a stylish NavBar similar to the examples depicted in the images (in AdobeXD it is di ...

Experiencing difficulties when trying to input text into a React text field

For a university assignment, I am using the create-react-app to build a website. I am facing issues with the input text field as I cannot type into it when clicked. There are no error messages indicating what could be wrong. The objective is for users to ...

Routing WebSocket connections with Node.js

Currently, I am in the process of developing a chat application for my company which will run on node js with websocket (ws). The app is designed to cater to various departments within the organization, each with its own set of users. My goal is to ensure ...

Error: Unable to locate npm package

I am currently working on an Angular application that was created using Grunt and relies on Bower and NPM. Recently, I attempted to install an npm module locally. The installation resulted in the files being stored in the main application directory under ...

Tips for creating a scrollable sidebar while ensuring that the deeply nested child pop-up element does not adhere to the scrollable properties

In my project, I am using Vue 3 along with Tailwind CSS and Headless UI. The challenge I am facing is making the sidebar navigation scrollable while ensuring that the pop-up menu appears outside the sidebar. As the number of menu items in the sidebar will ...

Retrieve information from an HTML webpage using Node.js

Currently, I am attempting to extract text from an HTML page using Node.js. Here is the URL. I am specifically looking to retrieve the string 0e783d248f0e27408d3a6c043f44f337c54235ce. Although I have tried a certain method, unfortunately, no data seems to ...

Unable to modify the SVG color until it has been inserted into a canvas element

There is an SVG code that cannot be modified: <?xml version="1.0" encoding="UTF-8"?> <svg id="shape" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32"> <path d="M29.57,19.75l-3. ...

The information overflow occurs outside the tooltip specifically in Chrome, while functioning perfectly in IE11

As a newcomer to the CSS world, I am experimenting with adding a block-level element (div) inside an anchor tag's :hover pseudo-class popup. The div element contains a table that needs to have dynamic sizing for both the table itself and its cells (wi ...