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 "
Related
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.
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?
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;
SUMMARY
I need to store both uploaded and server-generated images, with portable and
predictable paths so my server code is aware of where these images exist.
I need to generate URLs to these images that can be sent to the client. These URLs will be used in HTML image elements.
PROBLEM
My web application allows the user to upload an image, using gwtupload(Apache Commons). This image is stored on the server and a URL returned to the client so the image is shown. gwtupload provides a clientside method to get this URL for the uploaded image. This works in deployment; the following aspects do not:
In certain cases, the uploaded image must be cropped. This results in
a new image being generated by a servlet method. I want to store this
cropped image and return(to the client) an access URL.
Then, this image is used by another method to generate another
image. This method must know the location on the file system of
the previously uploaded(and/or cropped) image. A URL for the new
image must then be returned to client.
I have implementation working perfectly in GWT development mode. However, as I expected, after deployment to my own Tomcat server, the remote services fail due to my confusion regarding the file system. I do not know the correct way of storing these images in a predictable place on the server filesystem, nor do I know how to generate access URLs(for files residing outwith the WAR, as these images will.)
All these images are only needed for the current session, so the locations can be temporary directories. I have spent two days experimenting and trawling the web for a solution to no avail.
I will post abridged code below. This is my attempt to simply use the working directory and relative pathnames. Using the Eclipse debugger attached to my servlet container, I could see the results of String dataDir = context.getRealPath("foo") indicating a temp folder within the servlet: but when I navigated there using explorer, NONE of the files had been written to the disk. I am very confused.
public String[] generatePreview(String xml) {
PreviewManager manager = new PreviewManager();
String url;
try{
preview = manager.generatePreview(xml);
}
catch (Exception e){e.printStackTrace();}
//Create the preview directory
File folder = new File("previews");
if (!folder.exists()) folder.mkdir();
//The file to be written to
File output = new File(folder, "front.jpg");
ServletContext context = getServletContext();
String dataDir = context.getRealPath("previews");
try {
ImageIO.write(image, "jpg", output);
} catch (IOException e) {
e.printStackTrace();
}
url = "previews/" + output.getName();
return url;
}
#Override
public String cropBackground(int[] coord_pair, String relativePath) {
File backgroundsFolder = new File("backgrounds");
if (!backgroundsFolder.exists()) backgroundsFolder.mkdir();
ServletContext context = getServletContext();
String dataDir = context.getRealPath("backgrounds");
File current = new File(relativePath);
String croppedName = "cropped_" + relativePath.replace("./backgrounds/", "");
int x = coord_pair[0];
int y = coord_pair[1];
int width = coord_pair[2];
int height = coord_pair[3];
String croppedPath = null;
try {
croppedPath = imageCropper.createCroppedImage(current, "backgrounds", croppedName, x, y, width, height);
}
catch (IOException e){
e.printStackTrace();
}
current.delete();
return "backgrounds/" + croppedPath;
I am aware that my current 'return' statements would never work in deployment: I need to generate the URLs properly and return as strings. I'm sorry about the question length but I wanted to make my problem clear.
Choose a directory where your images will be stored, outside of Tomcat. Assign some unique ID to each uploaded or generated image, and store the images in this directory (with the ID as file name, for example).
Generate URLs to an image servlet that will read the image by ID in this directory, and send the bytes of the image to the output stream of the servlet response : image.action?id=theImageId.
I am currently working on an application, where users are given an option to browse and upload excel file, I am badly stuck to get the absolute path of the file being browsed. As location could be anything (Windows/Linux).
import org.apache.myfaces.custom.fileupload.UploadedFile;
-----
-----
private UploadedFile inpFile;
-----
getters and setters
public UploadedFile getInpFile() {
return inpFile;
}
#Override
public void setInpFile(final UploadedFile inpFile) {
this.inpFile = inpFile;
}
we are using jsf 2.0 for UI development and Tomahawk library for browse button.
Sample code for browse button
t:inputFileUpload id="file" value="#{sampleInterface.inpFile}"
valueChangeListener="#{sampleInterface.inpFile}" />
Sample code for upload button
<t:commandButton action="#{sampleInterface.readExcelFile}" id="upload" value="upload"></t:commandButton>
Logic here
Browse button -> user will select the file by browsing the location
Upload button -> on Clicking upload button, it will trigger a method readExcelFile in SampleInterface.
SampleInterface Implementation File
public void readExcelFile() throws IOException {
System.out.println("File name: " + inpFile.getName());
String prefix = FilenameUtils.getBaseName(inpFile.getName());
String suffix = FilenameUtils.getExtension(inpFile.getName());
...rest of the code
......
}
File name : abc.xls
prefix : abc
suffix: xls
Please help me in getting the full path ( as in c:.....) of the file being browsed, this absolute path would then be passed to excelapachepoi class where it will get parsed and contents would be displayed/stored in ArrayList.
Why do you need the absolute file path? What can you do with this information? Creating a File? Sorry no, that is absolutely not possible if the webserver runs at a physically different machine than the webbrowser. Think once again about it. Even more, a proper webbrowser doesn't send information about the absolute file path back.
You just need to create the File based on the uploaded file's content which the client has already sent.
String prefix = FilenameUtils.getBaseName(inpFile.getName());
String suffix = FilenameUtils.getExtension(inpFile.getName());
File file = File.createTempFile(prefix + "-", "." + suffix, "/path/to/uploads");
InputStream input = inpFile.getInputStream();
OutputStream output = new FileOutputStream(file);
try {
IOUtils.copy(input, output);
} finally {
IOUtils.closeQuietly(output);
IOUtils.closeQuietly(input);
}
// Now you can use File.
See also:
How to get the file path from HTML input form in Firefox 3
I remember to have some problem with this in the past too. If I am not mistaken, I think you cannot get the full file path when uploading a file. I think the browser won't tell you it for security purposes.