Skip to content

Instantly share code, notes, and snippets.

@denuno
Created June 26, 2013 02:11
Show Gist options
  • Save denuno/5864210 to your computer and use it in GitHub Desktop.
Save denuno/5864210 to your computer and use it in GitHub Desktop.
handle file upload as stream example
component {
jServletFileUpload = createObject("java","org.apache.commons.fileupload.servlet.ServletFileUpload");
jStreams = createObject("java","org.apache.commons.fileupload.util.Streams");
jByteArrayOutputStream = createObject("java","java.io.ByteArrayOutputStream");
function getFormItems() {
//var out = getPageContext().getResponse().getWriter();
var htRequest = getPageContext().getRequest();
var bao = jByteArrayOutputStream.init();
var contentLength = htRequest.getContentLength();
var contentType = htRequest.getHeader("Content-Type");
var isMultipart = jServletFileUpload.isMultipartContent(htRequest);
var items = [];
if(isMultipart){
var upload = jServletFileUpload.init();
var iter = upload.getItemIterator(htRequest);
var item = "";
var name = "";
var stream = "";
while (iter.hasNext()){
item = iter.next();
name = item.getFieldName();
stream = item.openStream();
if(item.isFormField()){
arrayAppend(items,{name:name, value:jStreams.asString(stream)});
}
else {
systemOutput("name==" & name);
if(!isNull(name) && name != ""){
var fileName = item.getName();
//var file = jFile.init(getServletContext().getRealPath("/" & fileName));
//var fos = jFileOutputStream.init(file);
var fileSize = jStreams.copy(stream, bao, true);
bao.close();
stream.close();
arrayAppend(items,{filename:fileName, fileSize:fileSize, bytes:bao});
}
}
}
}
return items;
}
}
@igal-getrailo
Copy link

nice! the only thing I would change is to use the for-in construct instead of the iterator's next(). at least theoretically it should work. e.g.:

for ( local.item in upload.getItemIterator(htRequest) ) {

    local.name = item.getFieldName();

    /* rest of the while loop contents...  */
}

then you can also remove the lines that set up [var item=""] and [var name=""]

@webRat
Copy link

webRat commented Jun 26, 2013

How do you two handle validation here?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment