This question already has an answer here:
Uploaded image only available after refreshing the page
(1 answer)
Closed 2 years ago.
My problem is that when I upload an image from one jsp and I go to another jsp which should show the image uploaded it doesn't show it. The image is uploaded and saved in my server, and I reference the correct path but for seeing the image I just need to restart tomcat.
Here is my uploader servlet(I think that it works correctly because the image is saved):
// Get file from form
Part part = request.getPart("cartel");
// Path
String ruta_local = getServletContext().getInitParameter("local_path");
String img_dir = getServletContext().getInitParameter("img_directory");
// Image name
String fileName = extractFileName(part);
// Add random number to image name
Random rand = new Random();
int random_numbers = rand.nextInt(1000);
fileName = NameOrExtension(fileName, "nombre") + String.format("%03d", (random_numbers))
+ "." + NameOrExtension(fileName, "extension");
request.getSession().setAttribute("foto", fileName);
// Final path
String cartel_path = ruta_local + File.separator
+ img_dir + File.separator + fileName;
File cartel = new File(cartel_path);
// File write
try (InputStream input = part.getInputStream()){
Files.copy(input, cartel.toPath());
input.close();
}
The images are saved in my img-carteles forlder which is in WebContent folder, and when I try to show an image knowing his name I use:
<img class="card-img-top" src="img-carteles/image_name" alt="Card image cap">
So I think that is a tomcat's rendering issue. Question: How can I show and uploaded image not having to restart tomcat?
The answer to this is the same as #BalusC's answer in Uploaded image only available after refreshing the page
In a nutshell, uploaded images should not be saved in the deployment folder.
Just changing the directory of the img-carteles directory to be outside the deployment folder should solve the problem.
Related
This question already has answers here:
Recommended way to save uploaded files in a servlet application
(2 answers)
Simplest way to serve static data from outside the application server in a Java web application
(10 answers)
Closed 5 years ago.
In my Servlet I need the client to upload a video or image in a form. I succeeded in uploading the file to the server in the following code. appPath is what I used first, however this is a bad path to permanently store these files since they will be deleted with every redeploy. For now I store them in the bin folder (appPath2). What folder would you guys suggest uploading to?
String appPath = request.getServletContext().getRealPath("");
String appPath2 = "path to tomcat folder/apache-tomcat-9.0.1/bin";
// constructs path of the directory to save uploaded file
String savePath = appPath2 + File.separator + "NotificationVideos";
File fileSaveDir = new File(savePath);
if (!fileSaveDir.exists()) {
fileSaveDir.mkdir();
}
String fileName = extractFileName(request.getPart("file"));
fileName = new File(fileName).getName();
this.createVideo((savePath + File.separator + fileName), notificationService.getHighestId());
request.getPart("file").write(savePath + File.separator + fileName);
}
private String extractFileName(Part part) {
String contentDisp = part.getHeader("content-disposition");
String[] items = contentDisp.split(";");
for (String s : items) {
if (s.trim().startsWith("filename")) {
return s.substring(s.indexOf("=") + 2, s.length()-1);
}
}
return "";
}`
Now my Actual Question:
I need to acces these videos or images in my JSP page. I save the path, "savePath + fileName" in a database. And I give the fileName as an attribute to the JSP page when loading the JSP page.
<video preload="auto" controls>
<source src="/NotificationVideos/${imageSrc}" type="video/mp4">
</video
It works great when i use a folder in the webapps folder. However i can't seem to make it work from a permanent folder outside webapps. I also tried
<Context docBase="path to tomcat folder/apache-tomcat-9.0.1/bin/NotificationVideos" path="/NotificationVideos"/>
Any ideas on how I can fix this?
I need some help with importing Images to my JavaFx application:
My image has the path : /sprinter/ExternalSprinterFolder/Maps/map_asteroid/map_asteroid.jpg
My GUI code has the path:
/sprinter/src/de/sprinter/gameclient/gui/SelectSectorGui.java
I tried already a lot but I can't load the image...
I tried for example:
File file = new File(imagePath);
Image image = new Image(file.toURI().toString());
ImageView iv = new ImageView(image);
and
String image = SelectSectorGui.class.getResource(imagePath).toExternalForm();
pane.setStyle(("-fx-background-image: url(\" " + image +
" \");-fx-background-repeat: no-repeat;"));
The first code block is the correct way to do this if the file will be on the file system, and not bundled as part of your jar file. In that case imagePath should be the absolute filesystem path to the file. You can check if the file exists with
System.out.println(file.exists());
The second code block is the correct way to do this if the image file will be bundled in your jar file. In this case, imagePath should be relative to the class; an path starting with / is interpreted as being relative to the classpath. If the path is incorrect in this case, getResource(...) will return null.
My Simple Website is using Spring MVC. The user uploads product images and thewebsite will display the image (with product name , price, etc..). The database only store the details of the image, and I store the image in a directory. The problem is, I am not sure where the image store should be.
// Creating the directory to store file
File dir = new File(imageDirectory);
if (!dir.exists())
dir.mkdirs();
// Create the file on server
File serverFile = new File(dir.getAbsolutePath()
+ File.separator + name);
For example, when the value of variable imageDirectory is "\temp", my application will store the image in "D:\temp" and i don know how to get the image url to show on my website
when the value of variable imageDirectory is "temp", my application store the image in "D:\soft\sts-bundle\sts-3.5.1.RELEASE\temp" and i dont know how to get the image url to show on my website
So where i should store upload image in and how do I get the uploaded image url (stored in the database) ?
In order to show your image to the end user, you must store it relative to your web app.
The ideal approach for it will be to have a dedicated folder in your webapp for storing uplaods and then sending the relative url to that folder to the end user.
E.g.
//request is an instance of HttpServletRequest
File uploadDirectory = new File(request.getSession().getServletContext().getRealPath("/uploads"));
if (!uploadDirectory.exists()) {
uploadDirectory.mkdirs();
}
File reportFile = new File(reportDirectory.getAbsolutePath(), fileName);
String requestUrl = request.getRequestURL().toString();
requestUrl = requestUrl.substring(0, requestUrl.lastIndexOf("/") + 1) + "uploads/" + fileName;
return requestUrl;
Given a standard text file that I read in with Scanner, where the first line contains the name of an image to read (which is located in the same folder as the text file), how can I use that file name to load the image to display on screen? As it stands right now, I'm getting a javax.imageio.IIOException saying "Can't read input file!" and I can't figure out why not.
Here's the text file:
MapBig.jpg
2
5
439 203 405 253 431 280 499 257 495 217
5
57 147 164 72 190 127 105 300 70 260
Here's my code to read it: image = ImageIO.read(new File(in.nextLine())); where in is an instance of Scanner.
I've also tried using ./MapBig.jpg in the text file and I get the same problem.
I suppose it should also be noted that I'm reading the text file using ClassLoader.getSystemResourceAsStream("map.data");, as this file is in a source folder in my project... same folder again as the file MapBig.jpg
Here's a stack trace when the error comes up:
javax.imageio.IIOException: Can't read input file!
at javax.imageio.ImageIO.read(Unknown Source)
at graphics.MapPanelSettings.<init>(MapPanelSettings.java:32)
at graphics.GameFrame.initialize(GameFrame.java:71)
at graphics.GameFrame.<init>(GameFrame.java:49)
at game.GameLauncher.main(GameLauncher.java:9)
The problem is indeed in the proper location.
You can construct proper path by getting location that you want to use with the ClassLoader :
URL url = ClassLoader.getSystemResource("map.data");
String fileName = in.nextLine();
String dirPath = new File(url.getPath()).getParent();
File myImage = new File(dirPath, fileName);
This should work. Sorry for incomplete original example.
Edit
Well, you don't actually need to calculate your path using "map.data" location. You directly use :
String fileName = in.nextLine();
URL imageUrl = ClassLoader.getSystemResource(fileName);
File myImage = new File(imageUrl.getPath());
Hope that helps.
try with this..
File file = new File(in.nextLine());
if(file.exists()){
image = ImageIO.read(file);
} else {
System.out.println("given file " + file.getName() + " not found.");
}
Your image has to be loaded from the file system, not from the .jar file itself. If your image is located elsewhere on your system (other directory than your .jar file is at), you should use a different file name than MapBig.jpg. You can change the file name in your map.data file, or you add the default directory as prefix to the loaded file name from your map.data file.
Whenever the files you want to load are loacated in the Jar file itself, you need to load them as resource. Check the example bellow:
URL imgUrl = getClass().getResource(in.nextLine());
ImageIcon imgIcon = new ImageIcon(imgUrl);
Image img = imgIcon.getImage();
If your image is located in a sub-directory, you need to prepend your file name with the proper directory path, for example:
URL imgUrl = getClass().getResource("resources/" + in.nextLine());
ImageIcon imgIcon = new ImageIcon(imgUrl);
Image img = imgIcon.getImage();
You should also debug whether the file name that needs to be loaded is correct. For example, temporarily replace your image = ImageIO.read(new File(in.nextLine())); line with System.out.println("File to load: " + in.nextLine().toString()); and make sure this name is correct. You can easily use the following script to automatically check whether the file (you're trying to load) exists, and print an error if that's not the case;
File f = new File(in.nextLine());
if(f.exists() && f.isFile())
image = ImageIO.read(f);
else
System.out.println("Unable to load image, file doesn't exist: " + f.getName());
This question already has answers here:
How to save generated file temporarily in servlet based web application
(2 answers)
Simplest way to serve static data from outside the application server in a Java web application
(10 answers)
Closed 5 years ago.
I am using Eclipse dynamic web project with tomcat 7. I am extremely new at this and slowly working through tutorials.
I am trying to make a simple webapp where a user enters information which is used to generate a QR code. I can make the image and save it to the WebContent folder. I want to show this image to the user and store it. Eventually I will have an account for each user with their stored QR codes and other images. I have an index.html that takes the information through a form and passes it to a servlet that creates the image and saves it in my WebContent folder, then builds a simple HTML to show the image. However, the image is not shown unless I tell eclipse to refresh the project. My guess is that eclipse doesn't know about the new image file until it gets refreshed, and for some reason the HTML generated by the servlet isn't picking up on the image even though it's in the right place.
The answer here suggests storing the data outside the webapp folders and streaming it. This is something I am unfamiliar with. I have tried to store the image in an outside folder and refer to it using both absolute and relative paths from the WebContent folder to the image file, neither works. And the QR code I was able to show from inside the WebContent folder doesn't update when I give it different data to build the image from, I have to refresh the project in eclipse even though the file name and location is the same. When I use the file browser to open the image file it has the new data.
I am asking for very basic help, I'm not incompetent but I've never done internet programming before and this is a lot to learn. In general I need to know how to get and store data and generate new data and then call it back up dynamically to display to the user. Thank you.
Here is my doPost method for the servlet:
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
username = request.getParameter("userName");
password = request.getParameter("password");
PrintWriter out = response.getWriter();
response.setContentType("text/html");
// check the input and create the html
checkFormData();
// Unless something goes very wrong, this string should be replaced.
String html = "<html><p>SOMETHING BROKE!</p></html>";
if(usernameOK && passwordOK){
html = buildHTMLForGoodInfo();
}else{
html = buildHTMLForBadInfo();
}
out.println(html);
}
And here is where I generate the QR code and create the HTML to display it:
private String buildHTMLForGoodInfo(){
QRGenerator qrg = new QRGenerator();
// This file goes into the webcontent folder
File filename1 = new File("/home/NAME/Workspace/MyWebApp/WebContent/qr1.png");
// This file goes outside the webcontent folder
File filename2 = new File("/home/NAME/Workspace/Data/qr2.png");
String result = "User Name = " + username + " Password = " + password +".";
qrg.makeQR(result, filename1);
qrg.makeQR(result, filename2);
String html = "<html><head><title>Results Page</title></head>\n" +
"<body><center>\n" +
"<p>Your user name is " + username + ".<p>\n" +
"<br/>\n" +
"<p>Your password is " + password + ".<p>\n" +
"<br/>\n" +
"<p> Have a QR Code</p>\n" +
"<br/>\n" +
// Show the image from inside the webcontent folder
"<img src=\"qr1.png\" alt=\"qr1.png\" border=\"1\">\n" +
// show the image from outside the webcontent folder
"<img src=\"/home/NAME/Workspace/Data/qr2.png\" alt=\"qr2.png\" border=\"1\">\n" +
"</center></body></html>";
return html;
}
NOTE: I have obfuscated my linux username to provide me with a tiny sense of false security.
Here is a screenshot of the output:
The QR code on the left decodes to old data, it should show the new data, username = UserName, password = Password. The image on the right does not appear. When I use the file manager to navigate to both file's locations on my computer, both files have QR codes with the correct data. I don't know where the old incorrect QR code is being stored, it doesn't show up in the file manager and I have checked for hidden files.
EDIT:
I have solved my issue by using an image servlet, unfortunately I can't find the stackoverflow page that led me in that path. I made a simple servlet with this doGet method:
#Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
// In the event of an error, make a red square.
int[] pixels = new int[128*128*3];
for(int i = 0; i < 128*128; i++){
pixels[i] = 200 << 16 | 0 << 8 | 0;
}
BufferedImage image = new BufferedImage(128,128,BufferedImage.TYPE_INT_RGB);
image.setRGB(0,0,128,128, pixels,0,128);
// get the file's address from the request
File imageID = new File(request.getParameter("imageID"));
// Try to read the file into the image, if you can't read it, print an error
try{
image = ImageIO.read(imageID);
}catch(Exception e){
System.out.println("IMAGE IO ERROR");
e.printStackTrace();
}
System.out.println(imageID.toString());
// get the response output stream and pass the image to it
ServletOutputStream out = response.getOutputStream();
ImageIO.write(image, "png", out);
}
Then when I want to display an image, I use this html:
img src=\"ImageServlet?imageID= PUT YOUR IMAGE ADDRESS HERE "