I have a file uploader on my website, since i cannot use php I’m using jsp pages.
My main page uses a hidden iframe to post data to a second jsp page that handles the upload. However the uploaded images is always corrupted, more specifically it’s larger in size than the original file.
Any hints or tips would be appreciated.
Main page code:
<form id="uploadForm">
<input type="file" name="datafile" /></br>
<input type="button" value="upload" onClick="fileUpload(document.getElementById('uploadForm'),'single_upload_page.jsp','upload'); return false;" >
</form>
The code for fileUpload concerning the form:
form.setAttribute("target","upload_iframe");
form.setAttribute("action", action_url);
form.setAttribute("method","post");
form.setAttribute("enctype","multipart/form-data");
form.setAttribute("encoding","multipart/form-data");
// Submit the form...
form.submit();
The code that handles the upload:
DataInputStream in = new DataInputStream(request.getInputStream());
int dataLength = request.getContentLength();
Because of the varying size of dataLength I’m assuming that the request.getInputStream receives extra data.
I only posted the code I think matters, if I need to post more or if you need any more information don’t hesitate to ask.
Simple request
The problem is request.getContentLength() gives the length of the whole request, containing headers and all.
You have to search for Content-Length header value, convert it to Long and that’s the proper size.
if you can’t get it (it can be unavailable) simply consume the whole input stream. But of course, you’ll not have idea of the file size.
Multipart request
Anyway… as your form is multipart/form-data you should use some library to parse all the different parts, find the one you need (the file part) and read it. You can use commons-fileupload.
Sample from real life