I have uploaded a file from my system, I have converted the file in bytes. Now I want to save that file at server. How can I do this. I have searched through the internet but found nothing. Is there any solution of this problem?
I am uploading file using JSP.
If you are talking about UploadedFile, here is how I achieved this after a huge internet search:
/**
* Save uploaded file to server
* #param path Location of the server to save file
* #param uploadedFile Current uploaded file
*/
public static void saveUploadedFile(String path, UploadedFile uploadedFile) {
try {
//First, Generate file to make directories
String savedFileName = path + "/" + uploadedFile.getFileName();
File fileToSave = new File(savedFileName);
fileToSave.getParentFile().mkdirs();
fileToSave.delete();
//Generate path file to copy file
Path folder = Paths.get(savedFileName);
Path fileToSavePath = Files.createFile(folder);
//Copy file to server
InputStream input = uploadedFile.getInputstream();
Files.copy(input, fileToSavePath, StandardCopyOption.REPLACE_EXISTING);
} catch (Exception e) {
logger.error(e.getMessage());
} finally {
}
}
Related
Map<String, String> zip_properties = new HashMap<>();
zip_properties.put("create", "false");
URI zip_disk = URI.create(name);
/* Create ZIP file System */
try (FileSystem zipfs = FileSystems.newFileSystem(zip_disk, zip_properties))
{
Path pathInZipfile = zipfs.getPath(name);
// System.out.println("About to delete an entry from ZIP File" +
pathInZipfile.toUri() );
Files.delete(pathInZipfile);
//System.out.println("File successfully deleted");
} catch (IOException e) {
e.printStackTrace();
}
I have create zip folder for multiple images in internal storage.Now i want to delete Zip files from the location and recreate same name zip folder in android.
Perform above code for delete zip folder but its not working
Please help me if anyone have solution
Thanks in advance..
after using delete() method in your File.
filePath is a String containing the path to your zip file.
File file = new File(filePath);
//must check if deleted is true. It is true if the file was successfully deleted
boolean deleted = file.delete();
Use below method
/**
* Clear/Delete all the contents in file/Directory
*
* #param file file/folder
* #return true on successfull deletion of all content
* <b>Make sure file it is not null</b>
*/
public boolean clearDirectory(#NonNull File file) {
boolean success = false;
if (file.isDirectory())
for (File child : file.listFiles())
clearDirectory(child);
success = file.delete();
return success;
}
Give this a try!
public static final String ZIP_FILES_DIR = "Download/FolderNAME";
File directoryPath = new File(Environment.getExternalStorageDirectory()+ File.separator + ZIP_FILES_DIR);
if (directoryPath.delete()) {
//do whatever you want
}
File file = new File(deleteFilePath);
boolean deleted = = file.deleted();
deleteFilePath is a String containing the path to your zip file.
if deleted is true. It is true if the file was successfully deleted.
I'm learning about Google Api for uploading file on Android and did find the good sample about it.(you can take a look on that sample here:
https://github.com/sdivakarrajesh/Uploading-Files-to-Google-drive-using-java-client-api-in-Android/blob/master/app/src/main/java/com/dev/theblueorb/usingdrivejavaapi/DriveActivity.java)
However, it's only show how to upload files, not how to select the file and upload it to GG drive. Here are the code for uploading and creating folder on GG drive:
private void uploadFile() throws IOException {
File fileMetadata = new File();;
fileMetadata.setName("Sample File");
fileMetadata.setMimeType("application/vnd.google-apps.spreadsheet");
// For mime type of specific file visit Drive Doucumentation
file2 = new java.io.File(path);
InputStream inputStream = getResources().openRawResource(R.raw.template);
try {
FileUtils.copyInputStreamToFile(inputStream,file2);
} catch (IOException e) {
e.printStackTrace();
}
FileContent mediaContent = new FileContent("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",file2);
File file = mService.files().create(fileMetadata, mediaContent)
.setFields("id")
.execute();
Log.e(this.toString(),"File Created with ID:"+ file.getId());
Toast.makeText(getApplicationContext(),
"File created:"+file.getId() , Toast.LENGTH_SHORT).show();
}
}
private void createFolderInDrive() throws IOException {
File fileMetadata = new File();
fileMetadata.setName("Sample Folder");
fileMetadata.setMimeType("application/vnd.google-apps.folder");
File file = mService.files().create(fileMetadata)
.setFields("id")
.execute();
System.out.println("Folder ID: " + file.getId());
Log.e(this.toString(),"Folder Created with ID:"+ file.getId());
Toast.makeText(getApplicationContext(),
"Folder created:"+file.getId() , Toast.LENGTH_SHORT).show();
}
Any body knows how to select the file on device, then upload it to selected folder on GG drive or the sample for that?
Referencing these docs for basic file upload, you should be able to "select the file on device" by specifying the complete file path as fileName in this line below:
java.io.File fileContent = new java.io.File(filename);.
For example, if you had a file called coolpic inside the directory media, you could use media/coolpic for the filename. The next doc I reference reinforces this strategy. The path will depend on the root location which, is something you can easily investigate.
Then, check out this doc for working with folders in Google Drive. You'll want to find the folder id and set this on upload using
fileMetadata.setParents(Collections.singletonList(folderId));
Note you can upload and then move in two steps, or use my method above and set the folder on upload.
i want to store uploaded file in a specific location in java. if i upload a.pdf then i want it to store this at "/home/rahul/doc/upload/". i went through some questions and answers of stack overflow but i am not satisfied with solutions.
i am working with Play Framework 2.1.2. i am not working with servlet.
i am uploading but it is storing file into temp directory but i want that file store into a folder as not a temp file i want that file like a.pdf in folder not like temp file.
public static Result upload() {
MultipartFormData body = request().body().asMultipartFormData();
FilePart filePart1 = body.getFile("filePart1");
File newFile1 = new File("path in computer");
File file1 = filePart1.getFile();
InputStream isFile1 = new FileInputStream(file1);
byte[] byteFile1 = IOUtils.toByteArray(isFile1);
FileUtils.writeByteArrayToFile(newFile1, byteFile1);
isFile1.close();
}
but i am not satisfied with this solution and i am uploading multiple doc files.
for eg. i upload one doc ab.docx then after upload it is storing temp directory and file is this:
and it's location is this: /tmp/multipartBody5886394566842144137asTemporaryFile
but i want this: /upload/ab.docx
tell me some solution to fix this.
Everything's correct as a last step you need to renameTo the temporary file into your upload folder, you don't need to play around the streams it's as simple as:
public static Result upload() {
Http.MultipartFormData body = request().body().asMultipartFormData();
FilePart upload = body.getFile("picture");
if (upload != null) {
String targetPath = "/your/target/upload-dir/" + upload.getFilename();
upload.getFile().renameTo(new File(targetPath));
return ok("File saved in " + targetPath);
} else {
return badRequest("Something Wrong");
}
}
BTW you should implement some checking if targetPath doesn't exist to prevent errors and/or overwrites. Typical approach is incrementing the file name if file with the same name already exists, for an example sending a.pdf three times should save the files as a.pdf, a_01.pdf, a_02.pdf, etc.
i just completed it. My solution is working fine.
My solution of uploading multiple files is :
public static Result up() throws IOException{
MultipartFormData body = request().body().asMultipartFormData();
List<FilePart> resourceFiles=body.getFiles();
InputStream input;
OutputStream output;
File part1;
String prefix,suffix;
for (FilePart picture:resourceFiles) {
part1 =picture.getFile();
input= new FileInputStream(part1);
prefix = FilenameUtils.getBaseName(picture.getFilename());
suffix = FilenameUtils.getExtension(picture.getFilename());
part1=new File("/home/rahul/Documents/upload",prefix+"."+suffix);
part1.createNewFile();
output = new FileOutputStream(part1);
IOUtils.copy(input, output);
Logger.info("Uploaded file successfully saved in " + part1.getAbsolutePath());
}
I'm using a library which wants a File() as an argument.
The file I want to pass it is one I want to package with my app, as part of the .jar
Is there any way to convert the JarEntry that I get from within my .jar to a File object I can pass?
If not and I have to copy the resource to disk temporarily, where's the best place to put the temporary file?
Thanks.
You cannot get a path to a file within a JARFile, only a stream, so you should extract it to the temporary directory and then pass that extracted file.
Here's a function I wrote to do this when I provided a db with a jar previously.
/**
* This method is responsible for extracting resource files from within the .jar to the temporary directory.
* #param filePath The filepath relative to the 'Resources/' directory within the .jar from which to extract the file.
* #return A file object to the extracted file
**/
public File extract(String filePath)
{
try
{
File f = File.createTempFile(filePath, null);
FileOutputStream resourceOS = new FileOutputStream(f);
byte[] byteArray = new byte[1024];
int i;
InputStream classIS = getClass().getClassLoader().getResourceAsStream("Resources/"+filePath);
//While the input stream has bytes
while ((i = classIS.read(byteArray)) > 0)
{
//Write the bytes to the output stream
resourceOS.write(byteArray, 0, i);
}
//Close streams to prevent errors
classIS.close();
resourceOS.close();
return f;
}
catch (Exception e)
{
System.out.println("An error has occurred while extracting the database. This may mean the program is unable to have any database interaction, please contact the developer.\nError Description:\n"+e.getMessage());
return null;
}
}
A File represents a real entry in the filesystem; a JarEntry doesn't exist on the file system. The mapping won't be there unless you extract the JAR entry to an actual file.
You can create a temp file using File.createTempFile. More details are available at this SO answer.
I get how you can use Expression Language to bind XPages controls to a Java Bean. Then it accesses the setters and getters automatically.
But how do you handle a file attachment?
What does that look like? I'd like to be able to I guess bind the file upload control to the bean. Save the attachment to "whatever" doc... whether it's the current or external document.. the bean should be able to handle that logic.
I guess I don't know how to get that file attachment into the in memory bean to be able to do anything with it like saving to a document.
any advice would be appreciated.
Update: This is a similar question to this: How to store uploaded file to local file system using xPages upload control?
But in that question the user wants to save to local disc. I'm looking to save to a document.
Thanks!
You need to create a getter and setter in the bean using the com.ibm.xsp.component.UIFileuploadEx.UploadedFile class:
private UploadedFile uploadedFile;
public UploadedFile getFileUpload() {
return uploadedFile;
}
public void setFileUpload( UploadedFile to ) {
this.uploadedFile = to;
}
In the function that processes the bean data (e.g. a save function) you can check if a file was uploaded by checking if the object is null. If it's not null, a file was uploaded.
To process that uploaded file, first get an instance of a com.ibm.xsp.http.IUploadedFile object using the getServerFile() method. That object has a getServerFile() method that returns a File object for the uploaded file. The problem with that object is that it has a cryptic name (probably to deal with multiple people uploading files with the same name at the same time). The original file name can be retrieved using the getClientFileName() method of the IUploadedFile class.
What I then tend to do is to rename the cryptic file to its original file name, process it (embed it in a rich text field or do something else with it) and then rename it back to its original (cryptic) name. This last step is important because only then the file is cleaned up (deleted) after the code is finished.
Here's the sample code for the steps above:
import java.io.File;
import com.ibm.xsp.component.UIFileuploadEx.UploadedFile;
import com.ibm.xsp.http.IUploadedFile;
import lotus.domino.Database;
import lotus.domino.Document;
import lotus.domino.RichTextItem;
import com.ibm.xsp.extlib.util.ExtLibUtil; //only used here to get the current db
public void saveMyBean() {
if (uploadedFile != null ) {
//get the uploaded file
IUploadedFile iUploadedFile = uploadedFile.getUploadedFile();
//get the server file (with a cryptic filename)
File serverFile = iUploadedFile.getServerFile();
//get the original filename
String fileName = iUploadedFile.getClientFileName();
File correctedFile = new File( serverFile.getParentFile().getAbsolutePath() + File.separator + fileName );
//rename the file to its original name
boolean success = serverFile.renameTo(correctedFile);
if (success) {
//do whatever you want here with correctedFile
//example of how to embed it in a document:
Database dbCurrent = ExtLibUtil.getCurrentDatabase();
Document doc = dbCurrent.createDocument();
RichTextItem rtFiles = doc.createRichTextItem("files");
rtFiles.embedObject(lotus.domino.EmbeddedObject.EMBED_ATTACHMENT, "", correctedFile.getAbsolutePath(), null);
doc.save();
rtFiles.recycle();
doc.recycle();
//if we're done: rename it back to the original filename, so it gets cleaned up by the server
correctedFile.renameTo( iUploadedFile.getServerFile() );
}
}
}
I have code that processes an uploaded file in Java. The file is uploaded with the normal fileUpload control and then I call the following Java code from a button (that does a full refresh - so that the document including the uploaded file is saved). In the Java code you can do whatever checks you want (filename, filesize etc.):
public void importFile() {
facesContext = FacesContext.getCurrentInstance();
ExternalContext externalContext = facesContext.getExternalContext();
// get a handle an the uploaded file
HttpServletRequest request = (HttpServletRequest) externalContext.getRequest();
String fileUploadID = JSFUtil.findComponent("uploadFile").getClientId(FacesContext.getCurrentInstance());
UploadedFile uploadedFile = ((UploadedFile) request.getParameterMap().get(fileUploadID));
if (uploadedFile == null) {
facesContext.addMessage("messages1", new FacesMessage(FacesMessage.SEVERITY_ERROR, "No file uploaded. Use the file upload button to upload a file.", ""));
return;
}
File file = uploadedFile.getServerFile();
String fileName = uploadedFile.getClientFileName();
// Check that filename ends with .txt
if (!fileName.endsWith(".txt")) {
facesContext.addMessage("messages1", new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error in uploaded file. The file must end with .txt", ""));
return;
}
try {
// Open the file
BufferedReader br;
br = new BufferedReader(new FileReader(file));
String strLine;
// Read File Line By Line
while ((strLine = br.readLine()) != null) {
// do stuff with the contents of the file
}
// Close the input stream
br.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
facesContext.addMessage("messages1", new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error in uploaded file. Please check format of file and try again", ""));
return;
}
facesContext.addMessage("messages1", new FacesMessage(FacesMessage.SEVERITY_INFO, "File successfully uploaded", ""));
}
With a handle on the file object you can store the file in other documents using embedObject.