#919 File Upload using Apache commons file upload

kaushik Sat 16 Jan 2010

#789 is on for Uploading files using wisp. Since I required a working code for a project I am working on now, I used FFI to use Apache Commons file upload to upload files for my project. I am contributing the code here for anybody who would need it... You can test the code using and HTML like this

<form action="http://localhost:8080/" method="post" enctype="multipart/form-data">
        <input id="f" name="f" type="file" />
      <input type="submit" />
</form>

Files are written to /files/tmp directory... You need to have Commons file upload and Commons IO in the classpath

using util
using web
using wisp

using [java]org.apache.commons.fileupload::FileItem;
using [java]org.apache.commons.fileupload::FileItemFactory;
using [java]org.apache.commons.fileupload.disk::DiskFileItemFactory;
using [java]org.apache.commons.fileupload::FileUpload
using [java]org.apache.commons.fileupload::RequestContext
using [java]java.io::InputStream
using [java]fanx.interop::Interop
using [java]java.util::Iterator
using [java]java.util::List
using [java]java.io::File as JFile

class FileServer : AbstractMain
{
  @opt="http port"
  Int port := 8080

  override Int run()
  {
    wisp := WispService
    {
      it.port = this.port
      it.root = HelloMod()
    }
    return runServices([wisp])
  }
}


//Class to wrap RequestContext
class MyRequestContext : RequestContext{
    WebReq? req
    new make(WebReq req){
       this.req = req
    }
    override Str? getCharacterEncoding(){
        return null
    }
    override Str? getContentType(){
       return req.headers["content-type"]
    }
    override Int getContentLength(){
        return req.headers["Content-Length"].toInt
    }
    override InputStream? getInputStream(){
        return Interop.toJava(req.in)
    }
}

const class HelloMod : WebMod
{


  override Void onPost(){
    res.headers["content-type"] ="text/html"

    //check if its a multi part request
    if(req.headers["content-type"].startsWith("multipart/")){
        factory := DiskFileItemFactory();
        upload := FileUpload(factory);

        List lst := upload.parseRequest(MyRequestContext(req));
        Iterator iterator := lst.iterator()
        FileItem[]? items := Interop.toFan(iterator);
        items.each |FileItem item|{
            Str name := item.getName
            file :=  JFile("/files/tmp/$name")
            item.write(file)
            res.out.print("File Written to /files/tmp/$name")
        }

        return
    }
    else{
        res.headers["content-type"] ="text/html"
        res.out.print("Not a Multi part request")
        return
    }

  }


}

Login or Signup to reply.