I have a formular in which there are 4 files that I need to upload.
Because I'm using OpenCms which automaticly uploads all files in a Folder i don't need to do that for my own.
The Problem now: I need an enctype="multipart/form-data" Formular, so the Software can upload it.
Now I can't read my Parameters with request.getParameter("") instead I'm using a List of FileItems and an Iterator.
But the List<FileItems> I get returns [].
Maybe you can help me with that Problem. Here's the Part of my Code:
private void createNachricht(CmsObject cms, HttpServletRequest request) {
System.out.println("execute createNachricht...");
List<CmsProperty> bildprops = new ArrayList<CmsProperty>();
List<CmsProperty> props = new ArrayList<CmsProperty>();
Map<String, String> allRequestData = new TreeMap<String, String>();
try {
if (ServletFileUpload.isMultipartContent(request)) {
System.out.println("isMultipartContent");
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload servletFileUpload = new ServletFileUpload(
factory);
#SuppressWarnings("unchecked")
List<FileItem> fileItemsList = servletFileUpload
.parseRequest(request); // returns [] so it's empty...
Iterator<FileItem> it = fileItemsList.iterator();
while (it.hasNext()) {
FileItem fileItemTemp = it.next();
if (!fileItemTemp.isFormField()) {
StringBuilder fileName = new StringBuilder(
sanitizeFilename(fileItemTemp.getName()));
System.out.println("fileName: " + fileName);
} else {
String name = fileItemTemp.getFieldName();
String val = fileItemTemp.getString("utf-8");
allRequestData.put(name, val);
System.out.println("name: " + name);
System.out.println("value: " + val);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
// more code here...
}
Files arrive in request stream that can be read once. I guess your CMS has already read this request stream, so it's now empty and ServletFileUpload can read nothing from it.
Ask your CMS for files. Refer to your CMS docs about how to get multi-part parameters that are parsed alongside uploaded files.
Related
I am using the spring framework to serve a file for download. I have the following code.
public ResponseEntity<List<Integer>>
defExport()
throws IllegalStateException,
IOException {
Map<String, Object> resultMap = Maps.newHashMap();
int status = STATUS_SUCCESS;
HttpHeaders headers = new HttpHeaders();
List<Integer> byteList = Lists.newArrayList();
try {
File file = transformService.executeExport(something);
byte[] fileContent = null;
try (InputStream is = new FileInputStream(file)) {
fileContent = read(is);
}
String fileName = StringUtils.join(something, ".xlsx");
headers.add("fileName", fileName);
headers.add("Content-Disposition", StringUtils.join(
"attachment; filename=\"", URLEncoder.encode(fileName, "UTF8"), "\""));
for (byte b : fileContent) {
byteList.add(new Integer(b));
}
} catch (Exception e) {
status = STATUS_ERROR;
}
headers.add("ifxResultStatus", String.valueOf(status));
return new ResponseEntity<>(byteList, headers, HttpStatus.OK);
on JS side, I have the follwing:
_self.xhr.open('POST', targetUrl, true);
_self.xhr.onreadystatechange = goog.bind(this.blankDlResponseHandler, this);
_self.xhr.setRequestHeader('X-CSRF-TOKEN', project.core.app.View.getCsrfToken());
var form_data = new FormData();
_self.xhr.send(form_data);
When I try to download the file with name greater than 255 characters, I can do so successfully in Chrome and IE11 on Windows 10.
However, when I try to do so in MS Edge, the download is unsuccessful due to the long file name.
How can I make it work on MS Edge also.
Edit
I just realized that in Chrome the file name is always limited to 218 characters and the last characters are trimmed.
So, my new question is how can I limit the characters to 218, specially in the case where a file with the same name already exists (file names are then appended (1),(2) and so on)
This question already has answers here:
Recommended way to save uploaded files in a servlet application
(2 answers)
Closed 6 years ago.
I want to avoid duplication while uploading file. If a file is updated then eventhough it has same name as which was uploaded previously, I should be able to upload that file on server.
I have written following servlet:
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
if (req.getParameter("from").equals("upload")) {
// checks if the request actually contains upload file
if (!ServletFileUpload.isMultipartContent(req)) {
PrintWriter writer = resp.getWriter();
writer.println("Request does not contain upload data");
writer.flush();
return;
}
// configures upload settings
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
ServletFileUpload upload = new ServletFileUpload(factory);
// constructs the directory path to store upload file
String uploadPath = getServletContext().getRealPath("") + File.separator + UPLOAD_DIRECTORY;
// creates the directory if it does not exist
File uploadDir = new File(uploadPath);
if (!uploadDir.exists()) {
uploadDir.mkdir();
}
try {
// parses the request's content to extract file data
List formItems = upload.parseRequest(req);
Iterator iter = formItems.iterator();
// iterates over form's fields
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
// processes only fields that are not form fields
if (!item.isFormField()) {
String fileName = new File(item.getName()).getName();
filePath = uploadPath + File.separator + fileName;
File storeFile = new File(filePath);
SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:sss");
System.out.println(f.format(storeFile.lastModified()));
System.out.println(storeFile.lastModified());
System.out.println(f.parse(f.format(storeFile.lastModified())));
File[] files = new File(
"C:\\bootcamp\\programs\\eclipse-jee-neon-RC3-win32-x86_64\\eclipse\\workspace\\.metadata\\.plugins\\org.eclipse.wst.server.core\\tmp0\\wtpwebapps\\excelFileManagement\\upload")
.listFiles();
int uploadFiles=0;
for (File file : files) {
if (fileName.equals(file.getName())) {
uploadFiles =1;
System.out.println("same");
DateFormat df = new SimpleDateFormat("yyyy-mm-dd hh:mm:sss");
String currentFile = df.format(storeFile.lastModified());
String storedFile = df.format(file.lastModified());
System.out.println("currentFile" + currentFile + "storedFile" + storedFile);
if (currentFile.contains(storedFile)) {
System.out.println("Same file cannot be uploaded again");
getServletContext().getRequestDispatcher("/Error.jsp").forward(req, resp);
} else {
// saves the file on disk
item.write(storeFile);
System.out.println("Upload has been done successfully!");
// Reading excel file
ReadingExcelFile rd = new ReadingExcelFile();
rd.readExcel(filePath);
getServletC
ontext().getRequestDispatcher("/DisplayTables.jsp").forward(req, resp);
}
}
}
catch (Exception ex) {
System.out.println("There was an error: " + ex.getMessage());
}}
However, I am getting same last modified date and time for both the files. And if a new file is uploaded storeFile.lastModified() returns Thu Jan 01 05:30:00 IST 1970 value
Can you confirm what is actual lastModified date of the file already uploaded by OS explorer ?
Second thing in SimpleDateFormat constructor arg m stands for minutes and M stands for month.Also S stands for millsecond.So your correct code would be
SimpleDateFormat("yyyy-MM-dd hh:mm:S")
Can you try with these changes and check ?
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to upload files to server using JSP/Servlet?
I'm implementing a fileupload servlet that is used alongside resumable.js
Everytime I try to read a file, I either get a NoSuchElement exception or a NumberFormatException with a string inside the file I'm reading. I'm sure I made a hiccup somewhere, but can't seem to tell
Here's a snippet of what I use to read request and write to file
if(ServletFileUpload.isMultipartContent(request)){
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setRepository(new File(temp_dir));
ServletFileUpload upload = new ServletFileUpload(factory);
Iterator<FileItem> iter = upload.parseRequest(request).iterator();
FileItem item = iter.next();
OutputStream out;
try {
out = new FileOutputStream(new File(dest_dir));
IOUtils.copy(item.getInputStream(), out);
logger.debug("Wrote file " + resumableIdentifier + " with chunk number "
+ resumableChunkNumber + " to " + temp_dir);
} catch (FileNotFoundException fnfe) {
fnfe.printStackTrace();
}
}
Did I do something wrong that is making the code actually read and interpret the contents of the file?
You have to iterate over the FileItems.
Right after this line:
Iterator<FileItem> iter = upload.parseRequest(request).iterator();
You should have something like this:
File dir = new File(dest_dir);
if (!dir.isDirectory()) dir.mkdirs();
while(iter.hasNext()) {
FileItem item = iter.next();
Also do not forget to close the output stream for every file item.
out = new FileOutputStream(new File(dir, item.getName()));
IOUtils.copy(item.getInputStream(), out);
out.close();
I want to do the following in tomcat 5.5
1. upload a excel file
2. process the file based on some crieteria
3. show the result
I am able to do all from 2 to 3 but not able to upload a file in tomcat 5.5 and could not also find example.
Pleaes help me.
Maybe you could give a try on Apache commons fileUpload
You can get an sample here
A more hands-on with not so much conceptual and clarification things could be found here.
On your Servlet you will just use something like:
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (isMultipart) {
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
try {
List items = upload.parseRequest(request);
Iterator iterator = items.iterator();
while (iterator.hasNext()) {
FileItem item = (FileItem) iterator.next();
if (!item.isFormField()) {
String fileName = item.getName();
String root = getServletContext().getRealPath("/");
File path = new File(root + "/uploads");
if (!path.exists()) {
boolean status = path.mkdirs();
}
File uploadedFile = new File(path + "/" + fileName);
System.out.println(uploadedFile.getAbsolutePath());
item.write(uploadedFile);
}
}
} catch (FileUploadException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
Apache has provided an API for uploading a file. You can try this.
http://commons.apache.org/fileupload/using.html
Use Apache’s Commons FileUpload and HttpClient.
Here some links to help you out.
http://www.theserverside.com/news/1365153/HttpClient-and-FileUpload
http://evgenyg.wordpress.com/2010/05/01/uploading-files-multipart-post-apache
https://stackoverflow.com/a/2424824/1438132
I have a servlet which is meant to handle the upload of a very large file. I am trying to use commons fileupload to handle it. Currently, the file I am attempting to upload is 287MB.
I set up the FileItemFactory and ServletFileUpload, then set a very large max file size on the ServletFileUpload.
Unfortunately, when I attempt to create a FileItemIterator, nothing happens. The form is set with the correct action, multipart encoding, and for the POST method.
Can anyone assist? doPost() of the servlet is posted below:
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// ensure that the form is multipart encoded since we are uploading a file
if (!ServletFileUpload.isMultipartContent(req)) {
//throw new FileUploadException("Request was not multipart");
log.debug("Request was not multipart. Returning from call");
}
// create a list to hold all of the files
List<File> fileList = new ArrayList<File>();
try {
// setup the factories and file upload stuff
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setFileSizeMax(999999999);
// create a file item iterator to cycle through all of the files in the req. There SHOULD only be one, though
FileItemIterator iterator = upload.getItemIterator(req);
// iterate through the file items and create a file item stream to output the file
while (iterator.hasNext()) {
// get the file item stream from the iterator
FileItemStream fileItemStream = iterator.next();
// Use the Special InputStream type, passing it the stream and the length of the file
InputStream inputStream = new UploadProgressInputStream(fileItemStream.openStream(), req.getContentLength());
// create a File from the file name
String fileName = fileItemStream.getName(); // this only returns the filename, not the full path
File file = new File(tempDirectory, fileName);
// add the file to the list
fileList.add(file);
// Use commons-io Streams to copy from the inputstrea to a brand-new file
Streams.copy(inputStream, new FileOutputStream(file), true);
// close the inputstream
inputStream.close();
}
} catch (FileUploadException e) {
e.printStackTrace();
}
// now that we've save the file, we can process it.
if (fileList.size() == 0) {
log.debug("No File in the file list. returning.");
return;
}
for (File file : fileList) {
String fileName = file.getName();
BufferedReader reader = new BufferedReader(new FileReader(fileName));
String line = reader.readLine();
List<Feature> featureList = new ArrayList<Feature>(); // arraylist may not be the best choice since I don't know how many features I'm importing
while (!line.isEmpty()) {
String[] splitLine = line.split("|");
Feature feature = new Feature();
feature.setId(Integer.parseInt(splitLine[0]));
feature.setName(splitLine[1]);
feature.setFeatureClass(splitLine[2]);
feature.setLat(Double.parseDouble(splitLine[9]));
feature.setLng(Double.parseDouble(splitLine[10]));
featureList.add(feature);
line = reader.readLine();
}
file.delete(); // todo: check this to ensure it won't blow up the code since we're iterating in a for each
reader.close(); // todo: need this in a finally block somewhere to ensure this always happens.
try {
featureService.persistList(featureList);
} catch (ServiceException e) {
log.debug("Caught Service Exception in FeatureUploadService.", e);
}
}
}
It was an incredibly stupid problem. I left the name attribute off of the FileUpload entry in the GWT UiBinder. Thanks for all of the help from everyone.
Are the only request parameters available File items? Because you may want to put in a check:
if (!fileItemStream.isFormField()){
// then process as file
otherwise you'll get errors. On the surface of things your code looks fine: no errors in the Tomcat logs?
You need to add enctype='multipart/form-data' in html form