Share uploaded file among servlets - java

Currently, I am having one jsp file, some java beans classes and two servlets.
The first servlet is responsible to upload a file and print out the context of it.
The second servlet is responsible for fetching the java beans code, execute it and print the result on jsp. However this concludes to duplicate code in servlets. Duplicated code is actually that the file need to be re-uploaded in order to call beans:
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
Iterator<FileItem> iterator = upload.parseRequest(request).iterator();
File uploadedFile = null;
String dirPath = "C:\\fileuploads";
while (iterator.hasNext()) {
FileItem item = iterator.next();
if (!item.isFormField()) {
String fileNameWithExt = item.getName();
File filePath = new File(dirPath);
if (!filePath.exists()) {
filePath.mkdirs();
}
uploadedFile = new File(dirPath + "/" + fileNameWithExt);
item.write(uploadedFile);
} else {
String otherFieldName = item.getFieldName();
String otherFieldValue = item.getString();
}
}
FileInputStream fstream = new FileInputStream(uploadedFile);
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
Next there is code which connects the servlet with the java beans. This works but my question is what is the best way to share this uploaded file? If I can store the file path in a variable and call it from the first servlet to second with no duplicated code.
Thanks in advance.
P.S I ve read this question as well, Share uploaded file between servlets in session , but i didnt really manage to do it.

If I can store the file path in a variable and call it from the first servlet to second with no
duplicated code.
So you would be just getting the file path and from second servlet you would be reading file again.
session.setAttribute("filePath",yourCalculatedFilePath);
and retrieve it from different servlet using
session.getAttribute("filePath");
You can just set the filePath in session attribute and you can access it across the session. but putting whole file into session isn't a good idea just imagine a user puts a file of size 1MB and there are 1000 users online at a time (just example) it would cost 1GB of server's memory.

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) {
...
}

Java: Overwrite the existing file on server with modified file(excel sheet) using File API

I have code that is designed to open a local master file, make additions, and save the file both by overwriting the master file and overwriting a write protected copy on an accessible network location.
But I am unable to replace the existing file on server. I have gone through other link on stackoverflow also like this but still no success.
Kndly assist me ! Rgds The code is
public class UploadAndSaveExcelAction extends Action
{
public ActionForward execute(
ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) throws Exception{
UploadAndSaveExcelForm myForm = (UploadAndSaveExcelForm)form;
String target = null;
if (myForm.getTheExcel().getFileName().length() > 0) {
FormFile myFile = myForm.getTheExcel();
System.out.println("" +myFile);
String fileName = myFile.getFileName();
byte[] fileData = myFile.getFileData();
//Get the servers upload directory real path name
String filePath = getServlet().getServletContext().getRealPath("/") +"Sheet\SparesUsed.xls";
/* Save file on the server */
//create the upload folder if not exists
File folder = new File(filePath);
if(folder.exists()){
System.out.println("Excel Sheet folder is existed therefore deleted");
folder.deleteOnExit();
}
String filePath1 = getServlet().getServletContext().getRealPath("/") +"Sheet";
File folder1 = new File(filePath1+"\\" + FileName);
System.out.println("Excel Sheet afterr delete folder is "+folder1);
boolean makedirectory=folder1.mkdir();
System.out.println(" Making Directory "+makedirectory);
if(!fileName.equals("")){
System.out.println("Server path for Excel :" +filePath);
//Create file
File fileToCreate = new File(filePath, fileName);
//If file does not exists create file
if(!fileToCreate.exists()){
FileOutputStream fileOutStream = new FileOutputStream(fileToCreate);
fileOutStream.write(fileData);
fileOutStream.flush();
fileOutStream.close();
target ="success";
} return mapping.findForward(target);}
You can use Spoon library.
I know it's been a while since the original post, but one of the more accessible looking Java transformation libraries appears to be Spoon(http://spoon.gforge.inria.fr/).
From the Spoon Homepage(http://spoon.gforge.inria.fr/):
Spoon enables you to transform (see below) and analyze (see example) source code. Spoon provides a complete and fine-grained Java metamodel where any program element (classes, methods, fields, statements, expressions...) can be accessed both for reading and modification. Spoon takes as input source code and produces transformed source code ready to be compiled.

How to store uploaded mulitple pdf file to a specific location in java?

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());
}

getServletContext().getRealPath("/") omitting forward slash (/)

I'm trying to upload a file from an HTML file input.
I am using Apache Commons FileUpload and the file uploads successfully. However, when I try storing the file path in my MySQL, it is storing it without file path code:
String uploadFolder = getServletContext().getRealPath("/");
String fileName = new File(item.getName()).getName();
filePath = uploadFolder+"/"+fileName;
File uploadedFile = new File(filePath);
This is how I'm trying to store the file.
sample filepath stored
C:UsersLashDesktopworkspace3.metadata.pluginsorg.eclipse.wst.server.core mp0wtpwebappsJavaECom/download doget.txt
I have no idea what this question is about, but the correct way to do the operations your posted code is doing is as follows:
File uploadFolder = new File(getServletContext().getRealPath("/"));
String fileName = new File(item.getName()).getName(); // not sure what's going on here
File uploadedFile = new File(uploadFolder, fileName);

FileNotFoundException while saving files in two separate folders

I'm using Spring and Hibernate. I'm uploading images using commons-fileupload-1.2.2 as follows.
String itemName = null;
String files = null;
String itemStatus="true";
Random rand=new Random();
Long randNumber=Math.abs(rand.nextLong());
Map<String, String> parameters=new HashMap<String, String>();
if (ServletFileUpload.isMultipartContent(request))
{
ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());
List<FileItem> items = null;
try
{
items = upload.parseRequest(request);
}
catch (FileUploadException e)
{
mv.addObject("msg", e.getMessage());
mv.addObject("status", "-1");
}
for(FileItem item:items)
{
if (!item.isFormField()&&!item.getString().equals(""))
{
itemName = item.getName();
parameters.put(item.getFieldName(), item.getName());
itemName = itemName.substring(itemName.lastIndexOf(File.separatorChar) + 1, itemName.length());
itemName=randNumber+itemName;
files = files + " " + itemName;
ServletContext sc=request.getSession().getServletContext();
File savedFile = new File(sc.getRealPath("images") , itemName);
item.write(savedFile);
File medium = new File(sc.getRealPath("images"+File.separatorChar+"medium") , itemName);
item.write(medium);
}
}
}
Where itemName is the name of the image file after parsing the request (enctype="multipart/form-data").
The image is first being saved in the images folder and then in the images/medium folder. It's not working causing FileNotFoundException but when I save only one file (commenting out one of them) either this
File savedFile = new File(sc.getRealPath("images") , itemName);
item.write(savedFile);
or this
File medium = new File(sc.getRealPath("images"+File.separatorChar+"medium") , itemName);
item.write(medium);
it works. Why doesn't it work to save both the files in separate folders at once?
I have not used apache commons-fileupload, but the apidoc for the function FileItem#write(File file) says, writing the same item twice may not work.
This method is not guaranteed to succeed if called more than once for
the same item. This allows a particular implementation to use, for
example, file renaming, where possible, rather than copying all of the
underlying data, thus gaining a significant performance benefit.
JavaDoc for DiskFileItem class says,
This method is only guaranteed to work once, the first time it is
invoked for a particular item. This is because, in the event that the
method renames a temporary file, that file will no longer be available
to copy or rename again at a later time.
You might also want to check out this JIRA:
DiskFileItem Jira Issue
References: FileItem JavaDoc, DiskFileItem JavaDoc

Categories

Resources