Reputation: 1184
Am uploading a mutlipart file to Google app engine using the below shown code. With the help of apache commons file uploader am uploading the file to Google app engine successfully. I want to validate the file size if it is 0 bytes or not. To do this i verified the Google app engine and the apache commons file uploader to check the file size but i got failed. Do we have any methods to find the file size. Kindly suggest me an idea.
My Servlet
ServletFileUpload upload = new ServletFileUpload();
FileItemIterator iter;
iter = upload.getItemIterator(request);
while (iter.hasNext()) {
item = iter.next();
String fileName = item.getName();
String fieldName = item.getFieldName();
if (item.isFormField()) {
String fieldValue = Streams.asString(item.openStream());
}
InputStream is1 = item.openStream();
try {
FileService fileService = FileServiceFactory.getFileService();
AppEngineFile file = fileService.createNewBlobFile(mime, fileName);
boolean lock = true;
FileWriteChannel writeChannel = fileService.openWriteChannel(file, lock);
byte[] b1 = new byte[BUFFER_SIZE];
int readBytes1;
while ((readBytes1 = is1.read(b1)) != -1) {
writeChannel.write(ByteBuffer.wrap(b1, 0, readBytes1));
}
writeChannel.closeFinally();
Upvotes: 2
Views: 240
Reputation: 80340
You need to read the whole is1
input stream into a byte buffer and see it's length. You can use this snippet:
public static byte[] getBytes(InputStream is) throws IOException {
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
int len;
byte[] data = new byte[10000];
while ((len = is.read(data, 0, data.length)) != -1) {
buffer.write(data, 0, len);
}
buffer.flush();
return buffer.toByteArray();
}
Upvotes: 1