This question already has answers here:
Recommended way to save uploaded files in a servlet application
(2 answers)
Closed 6 years ago.
Hello once again i ask question on stackOverflow :D
how can i upload file with JSF using primefaces?
i have method handle Upload Image
public void handleFileUpload(FileUploadEvent event) {
ExternalContext extContext = FacesContext.getCurrentInstance().
getExternalContext();
File result = new File(extContext.getRealPath
("//admin//item") + "//" + event.getFile().getFileName());
try {
FileOutputStream fileOutputStream = new FileOutputStream(result);
byte[] buffer = new byte[BUFFER_SIZE];
int bulk;
InputStream inputStream = event.getFile().getInputstream();
while (true) {
bulk = inputStream.read(buffer);
if (bulk < 0) {
break;
}
fileOutputStream.write(buffer, 0, bulk);
fileOutputStream.flush();
}
fileOutputStream.close();
inputStream.close();
FacesMessage msg = new FacesMessage("Succesful",
event.getFile().getFileName() + " is uploaded.");
FacesContext.getCurrentInstance().addMessage(null, msg);
} catch (IOException e) {
e.printStackTrace();
FacesMessage error = new FacesMessage("The files were not uploaded!");
FacesContext.getCurrentInstance().addMessage(null, error);
}
}
it work well but it just work when server deploy, when i upload image to server , folder //admin/item/ have image but when i re-start server i can't find image i was uploaded
and how can i display thumbnails for each item with each own image
but when i re-start server i can't find image i was uploaded
That's normal in most servletcontainer configurations. When you restart the server or redeploy the webapp, any previously expanded webapp files will be deleted and the WAR will be re-expanded. You shouldn't store uploaded files in the expanded folder for the case you'd like to keep them longer than the webapp context lives.
The normal practice is to store them in a fixed path outside the webapp context, e.g. /var/webapp/upload.
File file = new File("/var/webapp/upload", event.getFile().getFileName());
Unrelated to the problem, I'd suggest to make use of File#createTempFile() to avoid that another uploaded file which has -by coincidence- the same filename will overwrite any previously uploaded one.
Related
I'm having trouble fixing this issue,
I have created a Client\Server side application and created a Method where a user can
"Send" a PNG file from his side to Server side, then the Server side "Creates" and saves the image in a Package that only contains pictures.
When i run this Method of sending a Picture from Client side to Server side via Eclipse IDE
it works as expected, but when exporting Client/Server side into Runnable JAR files, i get the next error:
Java
private static void getImg(MyFile msg) {
int fileSize =msg.getSize();
System.out.println("length "+ fileSize);
try {
File newFile = new File(System.getProperty("user.dir")+"\\src\\GuiServerScreens\\"+msg.getFileName());
FileOutputStream fileOut;
fileOut = new FileOutputStream(newFile);
BufferedOutputStream bufferOut = new BufferedOutputStream(fileOut);
try {
bufferOut.write(msg.getMybytearray(), 0, msg.getSize());
fileOut.flush();
bufferOut.flush();
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
I get the follow error :
java.io.FileNotFoundException: java.io.FileNotFoundException: C:\Users\Ilya\Desktop\src\GuiServerScreens\test.png (The system cannot
find the path specified)
It seems that using File newFile = new File(System.getProperty("user.dir")+"\\src\\GuiServerScreens\\"+msg.getFileName());
Does not provide the wanted result
I think you are mixing what your directories look like in netbeans with what's available on the server. Save to an external directory instead, not to your src directory.
I'm writing this post because I need some help.
I'm having trouble display an image depending on a specific path in my App.
Basically what it's doing: I have a module named Sector, and each Sector can have an image related to it. When I use the Upload component of Vaadin, I save the path of the image to a table in my database so that it can display the picture chosen before.
The actual path of the image is weird, it seems that Vaadin copies the image to a dynamic random folder. It seems logical that it can't use the actual path of the image.
But here's the problem: The path is well entered in the Database, but when I reload the page (F5), Vaadin can't shows the image anymore. Which upsets me since it should display it well.
The path that Vaadin creates with the uploaded image : VAADIN/dynamic/resource/2/c1ef7b9d-8f2b-4354-a97e-fe1fd4e868e7/551434.jpg
I can put some code if it can help.
The screenshots show what it's doing once I'm refreshing the browser page.
The image is being uploaded
After refreshing the page
Here is the part of the code where I handle the upload image:
upload.addSucceededListener(e -> {
Component component = createComponent(e.getMIMEType(),
e.getFileName(), buffer.getInputStream());
showOutput(e.getFileName(), component, output);
//imgUpload = (Image) component;
InputStream inputStream = buffer.getInputStream();
targetFile = new File(PATH + currentProjetId + "\\secteur" + currentSecId + "\\photoSec.png");
try {
FileUtils.copyInputStreamToFile(inputStream, targetFile);
} catch (IOException e1) {
e1.printStackTrace();
Notification.show("Error");
}
System.out.println("PATH : " + targetFile.getPath());
});
I think you are using an in-memory resource that's discarded when you refresh the view. You have to take the contents of the file and save it in a file inside a directory in the server's file system. Here's an example:
FileBuffer receiver = new FileBuffer();
Upload upload = new Upload(receiver);
upload.setAcceptedFileTypes("text/plain");
upload.addSucceededListener(event -> {
try {
InputStream in = receiver.getInputStream();
File tempFile = receiver.getFileData().getFile();
File destFile = new File("/some/directory/" + event.getFileName());
FileUtils.moveFile(tempFile, destFile);
} catch (IOException e) {
e.printStackTrace();
Notification.show("Error").
}
});
This question already has answers here:
How do I create a file and write to it?
(35 answers)
Closed 1 year ago.
I'm working on a new function on a system, and at the moment I need to pick a file, and save on a folder in the user C:. The process happens as it follows, the user uploads a file into the system, that file can be anything, text, image, except videos, and now it is saved in the system database, but my boss wants to change that process so I need to save on a specific folder on the user C:, I already created the specific folder, but I don't know how to save the file in that created folder.
So the code for uploading a file as it follows:
public void uploadArquivo(FileUploadEvent event) {
byte[] bytes = null;
try {
File targetFolder = new File(System.getProperty("java.io.tmpdir"));
if (!targetFolder.exists()) {
if (targetFolder.mkdirs()) {
FacesMessageUtil.novaMensagem("Atenção", "Não foi possível criar pasta temporária!");
return;
}
}
targetFolder.mkdirs();
OutputStream out;
try (InputStream inputStream = event.getFile().getInputstream()) {
out = new FileOutputStream(new File(targetFolder, event.getFile().getFileName()));
int read;
bytes = new byte[10485760];
while ((read = inputStream.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
inputStream.close();
}
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace(System.out);
}
AnexoEmpreendimento anexo = new AnexoEmpreendimento();
anexo.setNomeArquivo(event.getFile().getFileName());
anexo.setTamanhoArquivo(event.getFile().getSize());
anexo.setArquivo(bytes);
anexos.add(anexo);
}
Well, it depends on what you actually 'have'. A web submit form? Which web framework do you have then? A BLOB in a db? Which DB engine do you have and which DB framework are you using in java to interact with it, etcetera.
Most libraries will let you obtain either an InputStream or a byte[] (if they offer both, you want the InputStream).
You can write an inputstream to a file, or a byte[] to a file, as follows:
import java.nio.file.*;
public class Example {
static final Path MY_DIR = Paths.get("C:/path/to/your/dir");
void writeByteArr(byte[] data) throws IOException {
Path toWrite = MY_DIR.resolve("filename.dat");
Files.write(toWrite, data);
}
void writeInputStream(InputStream data) throws IOException {
Path toWrite = MY_DIR.resolve("filename.dat");
Files.copy(data, toWrite);
}
}
In the unlikely case the data you 'get' is neither in byte[] nor InputStream form you're going to have to elaborate quite a bit on how the data gets to your code.
This question already has answers here:
Recommended way to save uploaded files in a servlet application
(2 answers)
Closed 7 years ago.
I'm writing a Java EE application, and I try to get an image from an URL then save it in my resource folder (thru an AJAX request).
My problem is if I don't reboot my server I'm not able to display this image because it isn't loaded on my server.
I'm using Tomcat 7, Spring, Hibernate, Primeface.
Here is my class to save myimage
public class ImageSaver {
final static int SIZE=1024;
public static void fileUrl(String fAddress, String localFileName, String destinationDir) {
OutputStream outStream = null;
URLConnection uCon = null;
InputStream is = null;
try {
URL url = new URL(fAddress);
byte[] buf;
int byteRead;
int byteWritten=0;
outStream = new BufferedOutputStream(new FileOutputStream(destinationDir+"\\"+localFileName));
uCon = url.openConnection();
is = uCon.getInputStream();
buf = new byte[SIZE];
while ((byteRead = is.read(buf)) != -1) {
outStream.write(buf, 0, byteRead);
byteWritten += byteRead;
}
}
catch (Exception e) {
e.printStackTrace();
}
finally {
try {
is.close();
outStream.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
public static void fileDownload(String fAddress,String fileName, String destinationDir){
int slashIndex =fAddress.lastIndexOf('/');
int periodIndex =fAddress.lastIndexOf('.');
//String fileName=fAddress.substring(slashIndex + 1);
if (periodIndex >=1 && slashIndex >= 0 && slashIndex < fAddress.length()-1){
}
else{
System.err.println("path or file name.");
}
}
}
and the way I call the function :
ImageSaver.fileDownload("http://www.mywebsite.com/myImage.jpg","myImage.jpg", "C:\\Users\\MyProject\\src\\main\\webapp\\resources\\images");
How can I automatically loaded on my serve my uploaded Image without any reboot ?
Which file allows the configuration of an upload folder ? And how ?
You should not write images retrieved dynamically into your webapp's folder - this opens you up for a whole category of problems. Instead, save them to a folder outside of the appserver's root directory and create a download servlet that will serve these resources.
The danger otherwise is that you'll retrieve some jsp file from external sources, save them to your appserver and on download the appserver will happily execute it server side.
Assume your webapp's directory to be non-writeable to your webapp. This will also ease backup and updates: Imagine you'll need to install an update or migrate to a different server: The application you have on your server will only partially be contained in its *.war file. If there's an explicit resource directory, you can back this up independently (or put it on a network share drive)
I want to create zip file of files which are present at one ftp location and Copy this zip file to other ftp location without saving locally.
I am able to handle this for small size of files.It works well for small size files 1 mb etc
But if file size is big like 100 MB, 200 MB , 300 MB then its giving error as,
java.io.FileNotFoundException: STOR myfile.zip : 550 The process cannot access the
file because it is being used by another process.
at sun.net.ftp.FtpClient.readReply(FtpClient.java:251)
at sun.net.ftp.FtpClient.issueCommand(FtpClient.java:208)
at sun.net.ftp.FtpClient.openDataConnection(FtpClient.java:398)
at sun.net.ftp.FtpClient.put(FtpClient.java:609)
My code is
URLConnection urlConnection=null;
ZipOutputStream zipOutputStream=null;
InputStream inputStream = null;
byte[] buf;
int ByteRead,ByteWritten=0;
***Destination where file will be zipped***
URL url = new URL("ftp://" + ftpuser+ ":" + ftppass + "#"+ ftppass + "/" +
fileNameToStore + ";type=i");
urlConnection=url.openConnection();
OutputStream outputStream = urlConnection.getOutputStream();
zipOutputStream = new ZipOutputStream(outputStream);
buf = new byte[size];
for (int i=0; i<li.size(); i++)
{
try
{
***Souce from where file will be read***
URL u= new URL((String)li.get(i)); // this li has values http://xyz.com/folder
/myPDF.pdf
URLConnection uCon = u.openConnection();
inputStream = uCon.getInputStream();
zipOutputStream.putNextEntry(new ZipEntry((String)li.get(i).substring((int)li.get(i).lastIndexOf("/")+1).trim()));
while ((ByteRead = inputStream .read(buf)) != -1)
{
zipOutputStream.write(buf, 0, ByteRead);
ByteWritten += ByteRead;
}
zipOutputStream.closeEntry();
}
catch(Exception e)
{
e.printStackTrace();
}
}
if (inputStream != null) {
try {
inputStream .close();
}
catch (Exception e) {
e.printStackTrace();
}
}
if (zipOutputStream != null) {
try {
zipOutputStream.close();
} catch (Exception e){
e.printStackTrace();
}
}
Can anybody let me know how I can avoid this error and handle large files
This is unrelated to file sizes; as the error says, you can't replace the file because some other process is currently locking it.
The reason why you see it more often with large files is because these take longer to transfer hence the chance of concurrent accesses is higher.
So the only solution is to make sure that no one uses the file when you try to transfer it. Good luck with that.
Possible other solutions:
Don't use Windows on the server.
Transfer the file under a temporary name and rename it when it's complete. That way, other processes won't see incomplete files. Always a good thing.
Use rsync instead of inventing the wheel again.
Back in the day, before we had network security, there were FTP servers that allowed 3rd party transfers. You could use site specific commands and send a file to another FTP server directly. Those days are long gone. Sigh.
Ok, maybe not long gone. Some FTP servers support the proxy command. There is a discussion here: http://www.math.iitb.ac.in/resources/manuals/Unix_Unleashed/Vol_1/ch27.htm