I am attempting to overwrite and update an image on a page whenever my end user would like. They would simply upload a new image, and it will replace the old with the same file name and then the src path in the web page does not need to change. However, it kind of works. The file overwrites. but when I refresh the page the image does not change to the new. The odd kicker is, When I go into my IDE (Eclipse) and double-click the new image file, THEN I can refresh the web page and it shows the new replaced one. This is my first job project, and I have not found the answer elsewhere.I will provide the code;
<img th:src="#{/img/uploadedFile.jpg}" alt="image"></img>
#RequestMapping(method=RequestMethod.POST, value="image")
public String processImageForm(#RequestParam("file") MultipartFile file,
RedirectAttributes redirectAttributes) {
if (file.isEmpty()) {
redirectAttributes.addFlashAttribute("message", "Please select a file to upload");
return "redirect:image";
}
String extension = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
Path path = Paths.get(UPLOADED_FOLDER + fileName + extension);
try {
Files.deleteIfExists(path);
} catch (IOException | SecurityException e) {
System.err.println(e);
}
try {
// Get the file and save it somewhere
byte[] bytes = file.getBytes();
Files.write(path, bytes);
redirectAttributes.addFlashAttribute("message", "You successfully uploaded '" + file.getOriginalFilename() + "'");
} catch (IOException e) {
e.printStackTrace();
}
return "redirect:image";
}
}
My guess would be that you are not copying that file to the correct location.
You know that in a web app the the war file is created and then deployed on a server. So in order to change something you need to change it on the server (even when running from Eclipse it creates a server context from you). I guess that's where your problem comes from - you copy the file to the wrong place.
And when you are running from Eclipse the file is properly replaced on your local file system but this doesn't change the deployed war application. When you double click it in Eclipse it notices the change and automatically redeploys it for you basically changing the file on the server.
Related
I am asking of there's a way how I could put like a program or a bat file or any file that has stuff written in it and them when he clicks on a button it will create that file that i have put into my project on to the users desktop is there a way?
File test = new File("C:/Users/"
+ System.getProperty("user.name")
+ "/AppData/Roaming/.minecraft/mods/welcome.txt");
try { test.createNewFile(); }
catch (IOException e1) { e1.printStackTrace(); }
this doesnt work.
If the file you want to creating is already exist in the disk, then you can print a message like the "File already exists" -
try {
File file = new File("c:\\some\location\file_name.txt");
if (file.createNewFile()){
System.out.println("File is created!");
}else{
System.out.println("File already exists.");
}
}catch (IOException e) {
e.printStackTrace();
}
In order to just put a file on an other computer you will need to be granted permission in some way to do that (otherwise anyone could just infect any networked computer with any content they desired). There are several ways you could gain access to an other computer (look into virtual private network and mapped network drive). The most common way of delivering files to another computer is to set up a web site where the user can request the file to be downloaded to their machine by clicking on a link. You could also write a client program that used an http get to allow the client user to request content be downloaded to a specific place on their machine.
ok i found out how i just downloaded the files from a server that i have "made"
I am generating .svg files in a Liferay portlet na saving them in a svg folder which is located on a server (JBoss AS). These files are generated and saved in a .java class, something like this:
private void saveSVG(Document doc, String fileName) {
// save svg to file
try {
File file = new File("svg/" + fileName + ".svg"); // make file
PrintWriter writer;
writer = new PrintWriter(new FileOutputStream(file)); // write and
// save file
DOMUtilities.writeDocument(doc, writer);
writer.flush();
writer.close();
System.out.println("File path: " + file.getPath());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
The file is saved in server/bin/svg directory. But when I try to access the file in my .jsp page, it cannot seem to find the file (its probably looking in another directory). How can I tell it, where the desired file is? I could use absolute path, store it somewhere and pass it to the .jsp page, but that doesnt seem like very elegant solution.
<object data="svg/topBar.svg" type="image/svg+xml"></object>
Or how can I save the file to a relative path where the .jsp page will find it using the upper code?
Thanks for any help!
EDIT: "topBar.svg" is obviously the fileName I am using in this example
The problem is that using new File() in the Java code, create the file in a location which is relative to the location of the command line when you started your JBoss while the path in the JSP is relative to your webapp context.
Not sure but I think you can try:
File file = new File(getPortletContext().getRealPath("svg/topBar.svg"))
I am developing a webapp (for mobile phones). There is one xhtml page, where I want to show a picture, which is stored locally on my hard drive (for example: D:\pictures\test.jpg).
Since browsers block images when they are located on a local harddrive, I wrote a method in my javabean, where the picture, stored on the localHD, is copied to the webApp directory, when the user enters the xhtml page. After the user leaves the page, the copied file inside the webapp should be deleted.
So when I'm running my app, copying works perfectly and the pictures are displayed correctly. However, when the files should get deleted, I get this errormessage:
java.nio.file.FileSystemException: D:\WebAppPath\src\main\webapp\resources\pics\test.jpg:
The process cannot be accessed because the file is being used by another process.
Strangely enough, after stopping and restarting the application I can delete the same image if it is still in the webApp directory. (But Only once; after re-copying it, I get the error message again.)
Also if I want to delete the file manually, by using Windows explorer, I get the error message that the file can't be deleted because it is used by Java(TM) Platform SE Binary.
So to delete the file (manually or via the bean) I have to wait for a restart of the application, which of course is not an acceptable solution for the end user.
I'm using JSF2.0 with Primefaces and Primefaces Mobile components. My IDE is Netbeans and I use Spring Webflow framework to navigate and trigger actions/methods between the xhtml pages.
Here's the code for the copying method in my JavaBean:
public void copyFotoToLocalhost() {
if (fotoList.size() > 0) {
for (int i = 0; i < fotoList.size(); i++) {
Foto tempPic = fotoList.get(i);
String tempItemName = tempPic.getItemName();
String originalFile = "D:\\localFilepath\\" + tempItemName;
String tempFileName = "D:\\WebAppPath\\src\\main\\webapp\\resources\\pics\\" + tempItemName;
File existTest = new File(tempFileName);
if (existTest.exists() == false) {
try {
File orFile = new File(originalFile);
File tempFile = new File(tempFileName);
InputStream in = new FileInputStream(orFile);
OutputStream out = new FileOutputStream(tempFile);
byte[] buf = new byte[8192];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
tempFile.setWritable(true);
System.out.println("File copied.");
} catch (FileNotFoundException ex) {
System.out.println(ex.getMessage() + " in the specified directory.");
System.exit(0);
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
}
}
Here's the code for the delete method:
public void deleteFotos() {
if (fotoList.size() > 0) {
for (int i = 0; i < fotoList.size(); i++) {
Foto tempPic = fotoList.get(i);
String tempItemName = tempPic.getItemName();
Path tempLocation = Paths.get("D:\\webAppPath\\src\\main\\webapp\\resources\\pics\\" + tempItemName);
fotoList.remove(i);
i--;
try {
Files.deleteIfExists(tempLocation);
System.out.println("sucessfully deleted" + tempPic.getItemName());
} catch (IOException ex) {
Logger.getLogger(WundDokuBean.class.getName()).log(Level.SEVERE, null, ex);
System.out.println("Fail # " + tempPic.getItemName());
}
}
fotoList.clear();
}
Do you have an idea, how to fix this?
I hope you understand my problem, if not please tell me which information you need, I'll try to provide it.
There is one xhtml page, where I want to show a picture, which is stored locally on my hard drive (for example: D:\pictures\test.jpg). Since browsers block images when they are located on a local harddrive (...)
I want to clear out a conceptual misunderstanding first: You seem to expect that it would work fine when the browser wouldn't have blocked it. This is completely untrue. You seem to expect that images are inlined in the HTML output. No, they are downloaded individually and independently from the HTML page. If you had continued to use local disk file system paths, then it would have worked only and only if your webpage visitor has also exactly the same file at exactly the same location at their disk file system. In reality, this is obviously not the case. It would only work if both the webbrowser and webserver runs at physically the same machine.
Coming back to your concrete problem of being unable to delete the file, it's is caused because the servletcontainer usually locks the files in expanded WAR folder. I can't tell the exact reason, but that's not relevant here as this whole approach is wrong anyway. This approach would fail when the deployed WAR file is not expanded on disk file system, but instead in server's memory. Also, hardcoding environment-specific disk file system paths is a bad idea. You'd need to edit, rewrite, recompile, rebuild the whole WAR everytime you change the environment. In other words, your webapp is not portable.
You need to keep the files there where they originally are and make them publicly available by a real URL. This can be achieved in 2 general ways:
Add a virtual host to the server config, pointing to D:\localFilepath\. How to achieve that depends on the server used. You didn't tell anything about the server make/version used, but using Spring suggests that you're not being able to use full Java EE stack and are likely using a barebones JSP/Servlet container such as Tomcat. In that case, it's a matter of adding the following line to its /conf/server.xml:
<Context docBase="D:\localFilepath" path="/fotos" />
This way they are available by http://localhost:8080/fotos/*.
Create a servlet which reads files from D:\localFilepath and writes to HTTP response. With Servlet 3.0 and Java 7 it's really a breeze. Here's a kickoff example (nullchecks/file-exist-checks/doHead()/caching/resuming omitted for brevity):
#WebServlet("/fotos/*")
public class FotosServlet extends HttpServlet {
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletExcpetion, IOException {
File file = new File("D:/localFilepath", request.getPathInfo().substring(1));
response.setHeader("Content-Type", getServletContext().getMimeType(file.getName()));
response.setHeader("Content-Length", String.valueOf(file.length()));
Files.copy(file.toPath(), response.getOutputStream());
}
}
That's basically it. This way they're available on http://localhost:8080/contextname/fotos/*.
I've got an issue with saving a BufferedImage using a simple paint program. When I save the image from the paint such as a picture of a snake that I drew earlier, it saves the image just fine, but it doesn't save it in the way you might think. Instead of saving the image to a C:\ drive (or whatever drive a user may be using) it saves the image to the eclipse workspace. This of course is unacceptable, as this needs to be given directly to a user's main place of access is. Here is the method that is used for saving the bufferedimage.
static void saveImage() {
try {
ImageIO.write(background, "png",
new File(fileName + ".png"));
} catch (IOException e) {
e.printStackTrace();
}
}
So here, background is obviously the image being saved, png is the extension, and fileName is a string that is saved earlier using a prior method that isn't important here. This method saves the image to the eclipse workspace. This is bad. We need this to save to the default drive. How do I accomplish this? Let me know if you need anything else to aid you with your answer.
EDIT: So, as requested, here is the code that changes the fileName. It is in a different class with a differnt UI completely, and because I'm not sure of how much to post, I'll post the actionListener and the getName() method. What happens here is that there is a JTextField that, once a JButton is pressed, has the string extracted from it and uses it as the fileName. Here's the code:
`finishButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ProgramUI.fileName = getName();
ProgramUI.fileHasName = true;
ProgramUI.saveImage();
frame.dispose();
}
});
}
public String getName() {
return nameField.getText();
}
`
Offer the user a JFileChooser (as seen in this answer) to allow them to navigate to a path and select a name.
Restrict the path using a FileSystemView as seen here.
You have not given the path to save the file when you are creating a File object. By default it will save the file in the current working directory.
Try this :
static void saveImage() {
try {
ImageIO.write(background, "png",
new File("C:\\" + fileName + ".png"));
} catch (IOException e) {
e.printStackTrace();
}
}
or better add a path parameter to the method:
static void saveImage(String filePath) {
try {
ImageIO.write(background, "png",
new File(filePath + fileName + ".png"));
} catch (IOException e) {
e.printStackTrace();
}
}
but make sure that you get the path with proper slashes (//)
If that code is saving to an Eclipse workspace, it is because:
you are supplying a relative pathname in filename, AND
the current directory is the Eclipse workspace directory when you run the application from within Eclipse.
Try running the command from the command prompt. With the same inputs (i.e. the same filename as you are currently using) it should save to the current directory.
It is not possible to give you a simple recipe for solving this problem. The correct solution depends on how you want the program to actually work:
Where (i.e. in what directory) you want the file to be saved.
Whether (and how) you want the user to be able to say where to save the file.
Whether this application needs to be portable; i.e. work on something other than Windows.
I suggest that you start by reading up on the concept of "the current directory", and read the javadoc for the java.io.File class ... which will explain how Java decides what file you "mean" when you try to open one.
I have written a java program which enabled the shared review feature on a pdf. After making the pdf as Shared Review PDF it sends the pdf to a link folder in UNIX machine (link folder means shortcut path of a folder). After that an shell script, which runs differently via crontab makes the pdf as comment enabled and via the script that pdf is copied to some folder.
Now the question is whenever I am copying the file in the UNIX link folder (for copying the file to the link folder I am using FileUtils.copyInputStream() function.), a comment enabled script is executing and doing all comment enabled things in pdf(.sh script in UNIX which runs not from my program.) but during saving the file it prompts the file is readonly and exits without saving the file. But if I do the same thing (putting the file manually to the link folder in UNIX) manually it makes the pdf file as Comment enabled. This is my sample code which sends the file to a folder.
try{
String outFname="SR_"+fname;
srEnabledIs = new FileInputStream(pdfoutputPath+fname);
if(srEnabledIs!=null && !path.equals("")){
Date today = new Date();
SimpleDateFormat format = new SimpleDateFormat("dd_MM_yyyy_hh_mm_ss_a");
String timeStamp=format.format(today);
FileUtils.copyInputStreamToFile(srEnabledIs, new File(path+outFname));
logtracker.writeDebugNormalLog("AnnotationMain","file copied to " + path);
try{
lrfile.renameTo(new File(pdfinputPath+"/pdf/"+fname.split("[.]")[0]+"_"+timeStamp+".pdf"));
}catch(Exception ex){
logtracker.writeDebugNormalLog("AnnotationMain", ex.getMessage());
ex.printStackTrace();
}
}else{
if(path.equals("")){
logtracker.writeDebugNormalLog("AnnotationMain", "File not copied as path not found.");
}
if(srEnabledIs==null){
logtracker.writeDebugNormalLog("AnnotationMain", "File not copied as InputStream is null.");
}
if(srEnabledIs==null && path.equals("")){
logtracker.writeDebugNormalLog("AnnotationMain", "File not copied as InputStream is null and path not found.");
}
}
}catch(IOException e){
logtracker.writeDebugNormalLog("AnnotationMain", e.getMessage());
e.printStackTrace();
}finally{
if(srEnabledIs!=null){
srEnabledIs.close();
}
}
But the same program is running and executing successfully in other UNIX machine. I am really unable to understand the situation. Please help me out of this situation.