java - How do I save an Uploaded Image to my C drive - java

This is a follow-up to what I was trying to accomplish here https://stackoverflow.com/questions/7313922/uploading-files-ussing-myfaces-tomahawk-jsf-2-0
I've managed to get the image as an UploadedFile Object, but I can't seem to be able to save it to disk. I want to save it locally (in C:\Temp, for example) such that when I run my app, I can upload a file (test.jpg, for example) from my desktop and see it saved on the server (for example, in C:\Temp).
My bean is pretty simple:
import org.apache.myfaces.custom.fileupload.UploadedFile;
public class PatientBB {
private UploadedFile uploadedFile;
public UploadedFile getUploadedFile(){
return this.uploadedFile;
}
.
public void setUploadedFile(UploadedFile uploadedFile){
this.uploadedFile = uploadedFile;
}
.
public String actionSubmitImage(){
//This is th part I need help with. how do I save it in my C?
}
I greatly Appreciate all the help, thank you!

As far as I can tell, according to the javaDoc, you should be able to do
uploadedFile.getInputStream();
and then push the data from that to a FileOutputStream.
Psuedo:
InputStream is = uploadedFile.getInputStream();
byte[] buffer = new byte[uploadedFile.getLength()); //This can be more space-efficient if necessary
is.read(buffer);
File f = new File("C:\\tmp\\" + uploadedFile.getFilename());
f.createNewFile();
FileOutputStream fos = new FileOutputStream(f);
fos.write(buffer);
Does that make sense? Is that what you're looking for?

The uploaded file can be copy to the specified location using java FileUtils API.
File theFile = new File("C:\temp\filename");
eg: FileUtils.copyFile(upload, theFile);

Related

Unable to save the uploaded file into specific directory

I want to upload files and save them into specific directory.And i am new to files concept.When i uploading files from my page they are saved in another directory(C:\Users\ROOTCP~1\AppData\Local\Temp\multipartBody989135345617811478asTemporaryFile) and not in specified directory.I am unable to set it.Please help me in finding a solution.For all help thanks in advance.
public static Result uploadHoFormsByHeadOffice() throws Exception {
Logger.info("#C HoForms -->> uploadHoFormsByHeadOffice() -->> ");
final String basePath = System.getenv("INVOICE_HOME");
play.mvc.Http.MultipartFormData body = request().body()
.asMultipartFormData(); // get Form Body
StringBuffer fileNameString = new StringBuffer(); // to save file path
// in DB
String formType = body.asFormUrlEncoded().get("formType")[0];// get formType from select Box
FilePart upFile = body.getFile("hoFiles");//get the file details
String fileName = upFile.getFilename();//get the file name
String contentType = upFile.getContentType();
File file = upFile.getFile();
//fileName = StringUtils.substringAfterLast(fileName, ".");
// path to Upload Files
File ftemp= new File(basePath +"HeadOfficeForms\\"+formType+"");
//File ftemp = new File(basePath + "//HeadOfficeForms//" + formType);
File f1 = new File(ftemp.getAbsolutePath());// play
ftemp.mkdirs();
file.setWritable(true);
file.setReadable(true);
f1.setWritable(true);
f1.setReadable(true);
//HoForm.create(fileName, new Date(), formType);
Logger.info("#C HoForms -->> uploadHoFormsByHeadOffice() <<-- Redirecting to Upload Page for Head Office");
return redirect(routes.HoForms.showHoFormUploadPage());
}
}
I really confused why the uploaded file is saved in this(C:\Users\ROOTCP~1\AppData\Local\Temp\multipartBody989135345617811478asTemporaryFile) path.
You're almost there.
File file = upFile.getFile(); is the temporary File you're getting through the form input. All you've got to do is move this file to your desired location by doing something like this: file.renameTo(ftemp).
Your problem in your code is that you're creating a bunch of files in memory ftemp and f1, but you never do anything with them (like writing them to the disk).
Also, I recommend you to clean up your code. A lot of it does nothing (aforementioned f1, also the block where you're doing the setWritable's). This will make debugging a lot easier.
I believe when the file is uploaded, it is stored in the system temporary folder as the name you've provided. It's up to you to copy that file to a name and location that you prefer. In your code you are creating the File object f1 which appears to be the location you want the file to end up in.
You need to do a file copy to copy the file from the temporary folder to the folder you want. Probably the easiest way is using the apache commons FileUtils class.
File fileDest = new File(f1, "myDestFileName.txt");
try {
FileUtils.copyFile(ftemp, fileDest);
}
catch(Exception ex) {
...
}

How to download a file from the internet using Java

Hi I am trying to write some code in my program so I can grab a file from the internet but it seems that is not working. Can someone give me some advice please ? Here is my code. In this case I try to download an mp3 file from the last.fm website, my code runs perfectly fine but when I open my downloads directory the file is not there. Any idea ?
public class download {
public static void main(String[] args) throws IOException {
String fileName = "Death Grips - Get Got.mp3";
URL link = new URL("http://www.last.fm/music/+free-music-downloads");
InputStream in = new BufferedInputStream(link.openStream());
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int n = 0;
while (-1!=(n=in.read(buf)))
{
out.write(buf, 0, n);
}
out.close();
in.close();
byte[] response = out.toByteArray();
FileOutputStream fos = new FileOutputStream(fileName);
fos.write(response);
fos.close();
System.out.println("Finished");
}
}
Every executing program has a current working directory. Often times, it is the directory where the executable lives (if it was launched in a "normal" way).
Since you didn't specify a path (in fileName), the file will be saved with that name in the current working directory.
If you want the file to be saved in your downloads directory, specify the full path. E.g.
String fileName = "C:\\Users\\YOUR_USERNAME\\Downloads\\Death Grips - Get Got.mp3";
Note how I've escaped the backslashes. Also note that there are methods for joining paths in Java. There is a way to get the current working directory in Java.

Program Not Creating File. What is Wrong?

I have tried creating a file, using the code below:
import java.io.File;
public class DeleteEvidence {
public static void main(String[] args) {
File evidence = new File("cookedBooks.txt");
However, the file cookedBooks.txt does not exist anywhere on my computer. I'm pretty new to this, so I'm having problems understanding other threads about similar problems.
You have successfully created an instance of the class File, which is very different from creating actual files in your hard drive.
Instances of the File class are used to refer to files on the disk. You can use them to many things, for instance:
check if files or directories exist;
create/delete/rename files or directories; and
open "streams" to write data into the files.
To create a file in your hard disk and write some data to it, you could use, for instance, FileOutputStream.
public class AnExample {
public static void main(String... args) throws Throwable {
final File file = new File("file.dat");
try (FileOutputStream fos = new FileOutputStream(file);
DataOutputStream out = new DataOutputStream(fos)) {
out.writeInt(42);
}
}
}
Here, fos in an instance of FileOutputStream, which is an OutputStream that writes all bytes written to it to an underlying file on disk.
Then, I create an instance of DataOutputStream around that FileOutputStream: this way, we can write more complex data types than bytes and byte arrays (which is your only possibility using the FileOutputStream directly).
Finally, four bytes of data are written to the file: the four bytes representing the integer 42. Note that, if you open this file on a text editor, you will see garbage, since the code above did not write the characters '4' and '2'.
Another possibility would have been to use an OutputStreamWriter, which would give you an instance of Writer that can be used to write text (non-binary) files:
public class AnExample {
public static void main(String... args) throws Throwable {
final File file = new File("file.txt");
try (FileOutputStream fos = new FileOutputStream(file);
OutputStreamWriter out = new OutputStreamWriter(fos, StandardCharsets.UTF_8)) {
out.write("You can read this with a text editor.");
}
}
}
Here, you can open the file file.txt on a text editor and read the message written to it.
File evidence = new File(path);
evidence.mkdirs();
evidence.createNewFile();
File is an abstract concept of a file which does not have to exist. Simply creating a File object does not actually create a physical object.
You can do this in (at least) two ways.
Write something to the file (reference by the abstract File object)
Calling File#createNewFile
You can also create temporary files using File#createTempFile but I don't think this is what you are trying to achieve.
You have only created an object which can represent a file. This is just in memory though. If you want to access the file you must us ea FileInputStream or a FileOutputStream. Then it will also be created on the drive (in case of the outputstream).
FileOutputStream fo = new FileOutputStream(new File(oFileName));
fo.write("test".getBytes());
fo.close();
This is just ur creating file object by using this object u need to call one method i.e createFile() method..
So use evidence.createNewFile(); if you are creating just file.
else if u want to create file in any specific location then specify your file name
i.e File evidence=new File("path");
In this case if ur specifying any directoty
String path="abc.txt";
File file = new File(path);
if (file.createNewFile()) {
System.out.println("File is created");
}
else {
System.out.println("File is already created");
}
FileWriter fw = new FileWriter(file, true);
string ab="Hello";
fw.write(ab);
fw.write(summary);
fw.close();

Java write data to a file and download it?

I am new bi to Java, facing an issue with desktop application. I have to write data and output it as "data.txt"(means without writing file to a fixed location) and let the user download this file. I had searched a lot over internet but didn't get any proper solution. All suggestions are welcome.
Note : I am using NetBeans IDE 7.0.1
Save the data in a stream and then display a FileChooser dialog to let the user decide where to save the file to. Then write the stream to the selected file.
More on file choosers can be read here: http://docs.oracle.com/javase/tutorial/uiswing/components/filechooser.html
Once you create your file on server you can then do a similar thing I did for sending image files to my clients (in my case it is a JSP but it really doesn't matter where your client is):
/**
* Writes file with a given path to the response.
* #param pathToFile
* #param response
* #throws IOException if there was some problem writing the file.
*/
public static void writeFile(String pathToFile, ServletResponse response) throws IOException {
try(InputStream is = new FileInputStream(pathToFile);
OutputStream out = new Base64OutputStream(response.getOutputStream());){
IOUtils.copy(is, out);
}
}
Those are the imports it uses:
import org.apache.commons.codec.binary.Base64OutputStream;
import org.apache.commons.io.IOUtils;
On the client (in your desktop app) you would use the same IOUtils to decode it from Base64 and then you can store it wherever you want.
For this bit actually #Matten gives a neat solution (+1).
I have example with JFileChooser but sorry still didn't get your point about the download thing.
BufferedOutputStream buff = null;
BufferedReader reader = null;
JFileChooser fileChooser;
File file;
fileChooser.showSaveDialog(this);
file = new File(fileChooser.getSelectedFile().toString());
file.createNewFile();
reader = new BufferedReader(new StringReader("String text"));
buff = new BufferedOutputStream(new FileOutputStream(file));
String str;
while ((str = reader.readLine()) != null) {
buff.write(str.getBytes());
buff.write("\r\n".getBytes());
}

Java Applet Download File

I am trying to build a java applet which downloads a file to the client machine. As a java application this code worked fine but when I tried as an applet it does nothing. I have signed the .jar file and am not getting any security error messages
The Code is:
import java.io.*;
import java.net.*;
import javax.swing.*;
public class printFile extends JApplet {
public void init(){
try{
java.io.BufferedInputStream in = new java.io.BufferedInputStream(new
java.net.URL("http://www.google.com").openStream());
java.io.FileOutputStream fos = new java.io.FileOutputStream("google.html");
java.io.BufferedOutputStream bout = new BufferedOutputStream(fos,1024);
byte data[] = new byte[1024];
while(in.read(data,0,1024)>=0)
{
bout.write(data);
}
bout.close();
in.close();
} catch(IOException ioe){
}
}
}
Can anyone help?
FileOutputStream fos = new FileOutputStream("google.html");
Change that to:
File userHome = new File(System.getProperty("user.home"));
File pageOutput = new File(userHome, "google.html");
FileOutputStream fos = new FileOutputStream(pageOutput); //see alternative below
Ideally you would put the output in either of:
A sub-directory (perhaps based on the package name of the main class - to avoid collisions) of user.home. user.home is a place where the user is supposed to be able to read & create files.
A path as specified by the end user with the help of a JFileChooser.
See this question,
Self Signed Applet Can it access Local File Systems
I believe it will help you, you need to write your code to use PrivilegedAction.
http://docs.oracle.com/javase/1.4.2/docs/api/java/security/PrivilegedAction.html

Categories

Resources