Uploading File in jsp or multipart/form-data - java

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?

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
}

Uploading file to server throws file or directory not found exception

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.

Commons FileUpload. Empty Items list

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

Upload file to S3

I'm trying to develop a file upload function on AWS.
I wrote a servlet to process post request, and the framework is shown below:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
boolean isMulti = ServletFileUpload.isMultipartContent(request);
if (isMulti) {
ServletFileUpload upload = new ServletFileUpload();
try {
FileItemIterator iter = upload.getItemIterator(request);
while (iter.hasNext()) {
FileItemStream item = iter.next();
InputStream inputStream = item.openStream();
if (item.isFormField()) {
} else {
String fileName = item.getName();
if (fileName != null && fileName.length() > 0) {
//read stream of file uploaded
//store as a temporary file
//upload the file to s3
}
}
}
} catch (Exception e) {
}
}
response.sendRedirect("location of the result page");
}
I think these classes should be used to upload files. I tried but in S3, the size of the file is always 0 byte. Are there any other ways to upload file with multiple parts?
InitiateMultipartUploadRequest
InitiateMultipartUploadResult
UploadPartRequest
CompleteMultipartUploadRequest
I refer to the code http://docs.aws.amazon.com/AmazonS3/latest/dev/llJavaUploadFile.html
I guess you are clubbing two things - one is getting the entire file to your app container (on the tomcat where your servlet is running) and the other is uploading the file to S3.
If you are able to achieve the first of the above tasks (you should have the file as a java.io.File object), the second task should be straightforward:
AmazonS3 s3 = new AmazonS3Client(awsCredentials);
s3.putObject(new PutObjectRequest(bucketName, key, fileObj));
This is S3's simple upload. S3 Multipartupload is where you divide the whole file into chunks and upload each chunk in parallel. S3 gives two ways to achieve a multipartupload.
Low level - where you take of chunking and uploading each part. This uses the classes you mentioned like InitiateMultipartUploadRequest
High level - In this S3 abstracts the process of chunking/uploading etc. using a TransferManager class

Creating directories problem

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 + "/";

Categories