Wednesday, August 25, 2010

FileUpload Streaming

I use Apache Commons FileUpload to upload files. I was doing it in the "traditional" way, using DiskFileItemFactory. One requirement I have is that I need to convert the stream to DataHandler, because it will then be passed to call web services with MTOM. This works perfectly fine with DiskFileItermFactory. However, with DiskFileItemFactory, you still need to setup a temp folder to save the file and also FileCleaningTracker to clean up. So I decided to give the streaming API a try.

I had to create FileItemStreamDataSource to wrap FileItemSteam for the purpose of creating a DataHandler.
package com.myapp.fileupload;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.activation.DataSource;

import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class FileItemStreamDataSource implements DataSource {
/**
* log.
*/
private Log log = LogFactory.getLog(getClass());

private FileItemStream stream;

public FileItemStreamDataSource(final FileItemStream stream) {
this.stream = stream;
}

@Override
public String getContentType() {
return stream.getContentType();
}

@Override
public InputStream getInputStream() throws IOException {
log.info("******** open stream **********");
return stream.openStream();
}

@Override
public String getName() {
return stream.getName();
}

@Override
public OutputStream getOutputStream() throws IOException {
throw new IOException();
}

}



There was no error in tests. However, when trying to open the file on the other end of web service, I found the content was either corrupted or empty (only 1KB). I wonder if this is because the stream was not read in full somehow. Maybe it is the same as the discussion here? Could it be that the stream is not kept open in web service calls? Anyway, I did not have enough time to get it work now and will need to revisit it later.

No comments:

Post a Comment