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?
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 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;
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 "
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.
Using Tomcat and Struts 2.
public FileAction class
{
......
public upload()
{
.....
String fullFileName = request.getContextPath() + "/productImages/" + filename;
File theFile = new File(fullFileName);
FileUtils.copyFile(upload, theFile);
.....
}
}
The problem is when I upload an image it will not add image in localhost:8085/shoppingCart/productImages and also not give any exception.
But when i write String fullFileName="c:upload/productImages/" + filename; it will save the file at c:upload/productImages/ path
mean working normal in c:upload/productImages/ case
If you want the file uploaded to the server's context, you need to use ServletContext.getRealPath(...) to find the base directory of the deployed application. Note that this will not work if you're deploying a war file. Uploaded files should go to an absolute location on the server itself.
For downloading an uploaded image you'd write a stream result (since you're using Struts 2) and use it to load and stream the uploaded file back to the client.