Commons FileUpload. Empty Items list - java

I use apache commons file-upload to upload files on servlet. But after parsing request I always get empty list of file items. My code looks like this:
if (!ServletFileUpload.isMultipartContent(request)) {
throw new UnsupportedOperationException("Expected `multipart/...` content-type header ");
}
ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());
List<FileItem> items = upload.parseRequest(request);
logger.debug("Items size: " + items.size());
Where can be problem? Request sent correctly

Add enctype="multipart/form-data" in your form action
<form action="UploadServlet" method="post"
enctype="multipart/form-data">
</form>
DiskFileItemFactory factory = new DiskFileItemFactory();
// maximum size that will be stored in memory
factory.setSizeThreshold(maxMemSize);
// Location to save data that is larger than maxMemSize.
factory.setRepository(new File("c:\\temp"));
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// maximum file size to be uploaded.
upload.setSizeMax( maxFileSize );
try{
// Parse the request to get file items.
List fileItems = upload.parseRequest(request);
}catch(Exception e){
}
http://www.tutorialspoint.com/servlets/servlets-file-uploading.htm

When creating the DiskFileItemDirectory use this this constructor
DiskFileItemFactory factory = new DiskFileItemFactory(FILE_SIZE, new File("/yourfolder"));
The FILE_SIZE is max file size you allow to upload. Make sure you have permissions to the folder location at "/yourfolder" (change this ...)

Related

Set default File to upload using Apache commons file upload

I am using apache commons file upload 1.1 . Currently i am using parseRequest(request) to parse the items from the request .
Now i have an additional request to upload a file . something like default file if user doesn't upload any.
Is that possible ?
Thanks in advance
parseRequest returns a list of FileItems. So, when the list is empty there was no file uploaded.
Therefore, you just need to test if the list is empty. Taking an example from Using FileUpload
ServletFileUpload upload = new ServletFileUpload(factory);
List<FileItem> items = upload.parseRequest(request);
if (items.isEmpty()) {
// process some default file
} else {
// process uploaded file
}
Update:
According to Processing the uploaded items, you can have files and regular form fields mixed in the request. You can iterate through the parameters, set a flag when you see a file upload, and act accordingly afterwards
// Process the uploaded items
boolean fileUploaded = false;
Iterator<FileItem> iter = items.iterator();
while (iter.hasNext()) {
FileItem item = iter.next();
if (item.isFormField()) {
processFormField(item);
} else {
processUploadedFile(item);
fileUploaded = true;
}
}
if (!fileUploaded) {
// process some default file
}

HTML upload file with Servlet

I need to upload a file by HTML but my form request has to include other parameters and values, for this i made the following:
I have the following html form:
<form action="CustomerAccountingServlet" method="post" name="payment_list_form" enctype="multipart/form-data">
<input type="hidden" name="action" value="save_payment" />
<input type="hidden" name="customer_id" value="123"/>
<input type="hidden" name="payment_id" value="444" />
<input type="file" name="invoice_file" />
<input type="submit" value="upload" />
</form
I use the following java code to get the file:
public static InputStream uploadFile(HttpServletRequest request, String fileFieldName) {
int maxFileSize = 5000 * 1024;
int maxMemSize = 5000 * 1024;
ServletContext context = request.getServletContext();
String filePath = context.getInitParameter("file-upload");
// Verify the content type
String contentType = request.getContentType();
if ((contentType.indexOf("multipart/form-data") >= 0)) {
DiskFileItemFactory factory = new DiskFileItemFactory();
// maximum size that will be stored in memory
factory.setSizeThreshold(maxMemSize);
// Location to save data that is larger than maxMemSize.
factory.setRepository(new File(filePath));
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// maximum file size to be uploaded.
upload.setSizeMax(maxFileSize);
upload.setHeaderEncoding("utf-8");
try {
// 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();
if (!fi.isFormField()) {
if(fi.getFieldName().equals(fileFieldName)){
return fi.getInputStream();
}
}
}
} catch (Exception ex) {
System.out.println(ex);
}
} else {
System.out.println("No file was found");
}
return null;
}
The problem that i get null when i do in the servlet the following:
request.getParameter("action");
request.getParameter("customer_id");
request.getParameter("payment_id");
Anyone can help please?
Thanks!
You cannot reference request parameters for multipart/form-data request in the conventional way. All the parameters are encoded in the multipart data, along with the uploaded file. See for example this blog post for an extended example of how this should be handled.

Uploading File in jsp or multipart/form-data

Actually I am trying to get no of files count to be uploading before uploading using common upload lib in jsp and I made a function for getting the counts of file this is here:
public static int getUploadFileCount(HttpServletRequest request) throws FileUploadException
{
int Result = 0;
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List<FileItem> items = upload.parseRequest(request);
for (FileItem item : items)
{
if (!item.isFormField())
Result++;
}
return Result;
}
And use this function in business logic this here:
public void doChangeProfilePhoto(HttpServletRequest request) throws FileUploadException
{
if(UploadFileUtil.getUploadFileCount(request) != 1)
throw new FileUploadException("There is Multiple/None File upload for Profile Photo. ");
ProfileImage newProfileImage = new ProfileImage();
newProfileImage.setFileName("sam.jpg");
if(new UploadBPOProfilePhotoImpl().uploadPhoto(newProfileImage, request))
{}
}
And in this code after calling uploadPhoto function there is also use same code for retrieving the files one by one like this:
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List<FileItem> items = upload.parseRequest(request);
for (FileItem item : items) // Did not get file if i already used this code once For getting the files count:
{
if (!item.isFormField())
//did for makeing file and writing/saving it with a name
}
So here I get problem is that when I use this code its not get file when I have used the same code for counting the files
and if I comment this two line where I have use to get files count in doChangeProfilePhoto like this:
//if(UploadFileUtil.getUploadFileCount(request) != 1)
// throw new FileUploadException("There is Multiple/None File upload for Profile Photo. ");
Then its working. Why its happening that if one time it is used so after it unable to retrieving the file.What's the reason behind it
and is there any way to count files using common upload...and also for their names?

File cannot be deleted .file is open in java tm SE library

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.

How can I read other parameters in a multipart form with Apache Commons

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?

Categories