Trying to upload a zipped multipart file. Writing in a particular location. But unable to delete the file. After unzipping.. Tried using fileObj.delete but no use !!
Just a sample code:
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(maxMemSize);
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setSizeMax(maxFileSize);
List fileItems = upload.parseRequest(request);
// Process the uploaded file items
Iterator i = fileItems.iterator();
while (i.hasNext())
{
FileItem fi = (FileItem) i.next();
if (!fi.isFormField())
{
fileName = FilenameUtils.getName(fi.getName());
String contentType = fi.getContentType();
long sizeInBytes = fi.getSize();
logger.info("File name is::"+fileName);
logger.info("content type is ::"+ contentType);
logger.info("size is::"+sizeInBytes);
// Write the file
fileObj = new File(dirObj, clientFileName+".zip");
fi.write(fileObj);
return fileObj;
You must close the file when done with it. Windows does not allow the deletion of open files.
Related
I am sending/ uploading a .tar.gz file as part of my upload POST request and I am able to retrieve all the files. However I want to add these extracted files as FileItem and NOT File in Java.
#RequestMapping(value="/import", produces="application/json", method=RequestMethod.POST)
#ResponseBody
public ca.alea.cam.api.model.Response import(#RequestPart("file") MultipartFile file) throws Exception, ContentRepositoryDaoException {
List<FileItem> list = new ArrayList<FileItem>();
List<File> fileList = new ArrayList<File>();
InputStream in = file.getInputStream();
GzipCompressorInputStream gzipIn = new GzipCompressorInputStream(in);
TarArchiveInputStream tarIn = new TarArchiveInputStream(gzipIn);
TarArchiveEntry entry;
while ((entry = (TarArchiveEntry) tarIn.getNextEntry()) != null) {
// I would like to add each entry/file in the MultipartFile tar
// as a FileItem and not File Object, which the next line currently is doing.
fileList.add(entry.getFile());
// I tried, list.add((FileItem) entry.getFile());, which didnt work
}
Any helpful suggestions please?
Image upload working on localhost fine using request.getRealPath() but same we are using in server that's not
working, because server can not find specified path.. image can't be displayed .. how i can solved this problem.??
here is code for image uploading:
filePath =request.getRealPath("") + "\\img\\";
System.out.println(filePath);
String contentType = request.getContentType();
if ((contentType.indexOf("multipart/form-data") >= 0))
{
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List fileItems = upload.parseRequest(request);
// message= fileItems.get(2).toString();
Iterator i = fileItems.iterator();
while (i.hasNext()) {
FileItem fi = (FileItem) i.next();
if(fi.isFormField())
{
message=fi.getString();
System.out.println("message is : "+message);
bean.setEmp_id(Integer.parseInt(message));
}
if (!fi.isFormField()) {
String fieldName = fi.getFieldName();
System.out.println("field name"+fieldName);
fileName = fi.getName();
if (fileName.lastIndexOf("\\") >= 0) {
file = new File(filePath
+ fileName.substring(fileName
.lastIndexOf("\\")));
} else {
file = new File(filePath
+ fileName.substring(fileName
.lastIndexOf("\\") + 1));
}
fi.write(file);
The getRealPath() gives the absolute path (on the file system) leading to a file specified in the parameters of the call. It returns the path in the format specific to the OS.
Read request#getRealPathfor its documentation.
Also it is advised to use servletRequest.getSession().getServletContext().getRealPath("/") instead of servletRequest.getRealPath("/") as it is deprecated.
so the best way is to provide the upload path for the server by yourself, as the method values specific to the OS the returned path may not be accessible(Permissions).
Hope this helps !!
Below is the code i have used to upload a file to the server. But the code throws a exception directory or file not found..
ResourceBundle rs_mail = ResourceBundle.getBundle("mail");
String upload_path = rs_mail.getString("upload_path");
File file = null;
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
// Parse the request to get file items.
List fileItems = upload.parseRequest(request);
// Process the uploaded file items
Iterator i = fileItems.iterator();
while (i.hasNext()) {
FileItem fi = (FileItem) i.next();
File uploadDir = new File(upload_path);
if (!uploadDir.exists()) {
uploadDir.mkdir();
}
file = new File(upload_path + file.separator + fi.getName());
fi.write(file);
}
Can any one point out the reason for the exception..
Contents of the property file
upload_path=../../../upload
Make sure you also create all the parent directories on the path to upload_path:
if (!uploadDir.exists()) {
uploadDir.mkdirs();
}
Note the use of mkdirs() instead of mkdir(). mkdir() will fail, if the parent structure does not exist. mkdirs() will also try to create the required parent directories.
You should also check for the return value, both methods will return false if the directory could not be created.
Can't figure out why this keeps creating 2 folders? It makes a '0' folder and whatever the jobID is from the html. I want uploaded files in the jobID folder, not the '0' folder.
int userID = 1; // test
String coverLetter = "";
String status = "Review";
int jobID = 0;
String directoryName = "";
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if(isMultipart && request.getContentType() != null)
{
// Create a factory for disk-based file items
FileItemFactory factory = new DiskFileItemFactory();
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// Parse the request
List /* FileItem */ items = null;
try
{
items = upload.parseRequest(request);
}
catch(FileUploadException e) {}
// Process the uploaded items
Iterator iter = items.iterator();
while(iter.hasNext())
{
FileItem item = (FileItem)iter.next();
if(item.isFormField())
{
if(item.getFieldName().equals("coverLetter"))
coverLetter = item.getString();
if(item.getFieldName().equals("jobID"))
jobID = Integer.parseInt(item.getString());
}
directoryName = request.getRealPath("/") + "/Uploads/CV/" + jobID + "/";
File theDir = new File(directoryName);
if (!theDir.exists())
theDir.mkdir();
if(item.getFieldName().equals("file"))
{
File uploadedFile = new File(directoryName + item.getName());
try
{
item.write(uploadedFile);
}
catch(Exception e) {}
}
}
Edit:
Problem solved.I want uploaded files
It was because it was in the jobID folder, not the '0' folder.
I suspect this isn't true:
item.getFieldName().equals("jobID")
It's a bit difficult to guess though. Have you tried debugging in Eclipse (or similar)? Adding some logging might help too.
There must be 2 items parsed from the request, So perhaps you are sending 2 upload items.
The first item doesn't have the jobID FieldName so the directory name remain
.../Uploads/CV/0
So thats the time which is causing problems.
The second item does have the job ID so the directory gets created correctly.
Can you post the form so we can see, it may be something on there. Is the cover letter an additional file without jobId?
You could solve it by only creating dir if jobID exists.
Try printing/logging the jobID before the below line:
directoryName = request.getRealPath("/") + "/Uploads/CV/" + jobID + "/";
I have a file upload form that is being posted back to a servlet (using multipart/form-data encoding). In the servlet, I am trying to use Apache Commons to handle the upload. However, I also have some other fields in the form that are just plain fields. How can I read those parameters from the request?
For example, in my servlet, I have code like this to read in the uplaoded file:
// Create a factory for disk-based file items
FileItemFactory factory = new DiskFileItemFactory();
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// Parse the request
Iterator /* FileItem */ items = upload.parseRequest(request).iterator();
while (items.hasNext()) {
FileItem thisItem = (FileItem) items.next();
... do stuff ...
}
You could try something like this:
while (items.hasNext()) {
FileItem thisItem = (FileItem) items.next();
if (thisItem.isFormField()) {
if (thisItem.getFieldName().equals("somefieldname") {
String value = thisItem.getString();
// Do something with the value
}
}
}
Took me a few days of figuring this out but here it is and it works, you can read multi-part data, files and params, here is the code:
try {
ServletFileUpload upload = new ServletFileUpload();
FileItemIterator iterator = upload.getItemIterator(req);
while(iterator.hasNext()){
FileItemStream item = iterator.next();
InputStream stream = item.openStream();
if(item.isFormField()){
if(item.getFieldName().equals("vFormName")){
byte[] str = new byte[stream.available()];
stream.read(str);
full = new String(str,"UTF8");
}
}else{
byte[] data = new byte[stream.available()];
stream.read(data);
base64 = Base64Utils.toBase64(data);
}
}
} catch (FileUploadException e) {
e.printStackTrace();
}
Did you try request.getParam() yet?