I have 4 input tags to upload 4 different files,
<form method="post" name="myform" action="upload" target="_blank" enctype="multipart/form-data" style="position: absolute; right: -5%; top: 2%;">
Left File : <input type="file" name="dataFile1" id="fileChooser1" /><br><br>
Right File : <input type="file" name="dataFile2" id="fileChooser2" /><br><br>
Config File :<input type="file" name="dataFile3" id="fileChooser3" /><br><br>
Geco File : <input type="file" name="dataFile4" id="fileChooser4" /><br><br><br>
<button type="button" onclick="ValidateFile()">Click to Upload</button>
</form>
Now on my Servlet.java side I want to rename the file which is being uploaded.
How do I do that? Using commons up loader.
PS: I've tried to get the name of the id of the input tag so that I can create an if loop and assign fileName name as required,
String my = request.getParameter("dataFile1");
System.out.println(my);
This print's null.
To figure out which file is which, use the FileItem that you get from ServletFileUpload#parseRequest , you can call the getFieldName method to get the value of the name attribute from the JSP snippet above.
To save the file with a particular name, create a File object with the correct name and call FileItem#write with that object.
This code is untested but should give you a place to start.
List items = upload.parseRequest(httpRequest);
Iterator iter = items.iterator();
File outputDir = getOutputDir();
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
String origName = item.getFieldName();
if ("dataFile1".equals(origName) {
File outputFile = new File(outputDir, "firstFile.txt"); // This bit is doing the renaming
item.write(outputFile);
} // ... else all the other inputs get handled ...
}
i think what you have to do is the following :
1st - parse the request to get a list of FileItem like the following :
List<FileItem> items = upload.parseRequest(request);
2nd - process the uploaded items like the following :
Iterator<FileItem> iter = items.iterator();
while (iter.hasNext()) {
FileItem item = iter.next();
if (item.isFormField()) {
processFormField(item);
} else if (!item.isFormField()) {
// Process a file upload
String fieldName = item.getFieldName();
String fileName = item.getName();
String contentType = item.getContentType();
boolean isInMemory = item.isInMemory();
long sizeInBytes = item.getSize();
//here you change the name of the uploaded file and then write it
File uploadedFile = new File(dir , "fileName");
item.write(uploadedFile);
}
}
and please check the documentation here in the section Processing the uploaded items .
and give me some feedback
Hope That Helps .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.