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;
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.
My form has an upload button for the user to save file images.
ServletContext context = ServletActionContext.getServletContext();
String appPath = context.getRealPath("");
String filePath = appPath+"\\images\\categories";
File fileToCreate = new File(filePath, getMyFileFileName());
FileUtils.copyFile(getMyFile(), fileToCreate);
I need to upload the picture and put it on the image/categories folder for future access. It is working well in my localbuild but when I deployed it on the cloud by uploading the .war file, it doesn't work anymore. It cannot find the image.
HTML Error upon accessiing the image is as follow
type Status report
message /Teapop/images/categories/team.png
description The requested resource (/Teapop/images/categories/team.png) is not available.
What am I doing wrong?
please try to use File.separator instead
String filePath = appPath+File.separator+"images"+File.separator+"categories";
and please give me some feedback
Hope that helps .
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 "
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.
Hi I want to make images invisible to android gallery or any third party gallery app, the image will be places in specific folder on SD card.
For example I have following code to save an image to a folder called myimages. I just want the images stored in myimages folder should not be visible to any gallery app and only my own application can access these images.
void saveBitmap(Bitmap bmp)
{
FileOutputStream os;
String dirName = "/mvc/mvc/myiamges/";
try {
if (android.os.Environment.getExternalStorageState().equals(
android.os.Environment.MEDIA_MOUNTED)){
String root = Environment.getExternalStorageDirectory()
.toString();
File dir = new File (root + dirName);
boolean created=dir.mkdirs();
//File file = new File(this.getExternalFilesDir(null),
// this.dirName+fileName);
//this function give null pointer exception so im
//using other one
File file = new File(dir, "aeg2.png");
os = new FileOutputStream(file);
}else{
os = openFileOutput("aeg2.png", MODE_PRIVATE);
}
bmp.compress(CompressFormat.PNG, 100, os);
os.flush();
os.close();
}catch(Exception e){
e.printStackTrace();
}
}
Rename those files with custom extensions like filename.extension.customextension
like hello.avi.topsecret.
When you need the file to be ready mode to play rename it to proper extension, play and rename it back.
This should work for you.
or
Prefix your folder name with a dot "."
Check these links for more info:
http://www.makeuseof.com/tag/hide-private-picture-folders-gallery-android/
Yes, save it with any extension you want or even without extension.
In your app, just read it as normal image file.
Create an empty file inside your image store folder named '.nomedia' <- atention to the initial point.
All media files sabed inside this folder will not be showed in galery browsers.