Showing posts with label FileUpload. Show all posts
Showing posts with label FileUpload. Show all posts

Saturday, October 10, 2015

Web Application for File Upload with streaming

This gives you an entire working example (worth 1000 user manual pages) http://www.codejava.net/java-ee/servlet/apache-commons-fileupload-example-with-servlet-and-jsp .... I have tested it and put in https://github.com/vernetto/WebFileUploader (just git clone it and run it).

Here the user guide of Apache FileUpload module:

http://commons.apache.org/proper/commons-fileupload/using.html

Create a webapp

Download commons-io jar http://commons.apache.org/proper/commons-io/download_io.cgi and commons-fileupload jar http://commons.apache.org/proper/commons-fileupload/download_fileupload.cgi and place them in WEB-INF/lib

Well actually rather than putting here snippets of code, here is the whole NON-Streaming example https://github.com/vernetto/WebFileUploader and here the STREAMING example https://github.com/vernetto/WebFileUploaderStreaming

I have tested with a 4GB file and memory occupation on the server (and Garbage Collection) was really minimal... transfer speed was also decent (say 2 minutes for a 4GB file....).

Here https://raw.githubusercontent.com/vernetto/WebFileUploaderStreaming/master/WebFileUploaderStreaming.war you can download the war file directly.



Thursday, March 10, 2011

Struts File Upload

http://wiki.apache.org/struts/StrutsFileUpload

in a nutshell:


in the JSP:


in the Action:

ProductUploadForm myForm = (ProductUploadForm) form;
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");



// Process the FormFile
FormFile myFile = myForm.getTheFile();
String contentType = myFile.getContentType();
String fileNameAbsolutePath    = myFile.getFileName();
int fileSize       = myFile.getFileSize();

logger.debug("uploading File Name: " + fileNameAbsolutePath + ", File Size: " + fileSize + ", contentType: " + contentType);
String fileName = new File(fileNameAbsolutePath).getName();
String newFileName = STAGING_DIR + fileName + sdf.format(new Date());

try {
 // copy the stream content to a File in a staging directory, adding timestamp to the file name
 File f2 = new File(newFileName);
 OutputStream out = new FileOutputStream(f2);
 InputStream in = myFile.getInputStream();
 byte[] buf = new byte[1024];

 int len;

 while ((len = in.read(buf)) > 0){
  out.write(buf, 0, len);
 }
 in.close();
 out.close();
 logger.debug("finished copying File Name: " + fileNameAbsolutePath);
} catch (Exception e) {
 logger.error("problem uploading file name : " + fileNameAbsolutePath, e);
}




and the Form contains an attribute
private org.apache.struts.upload.FormFile theFile;

with getter and setter