Uploading and Downloading Blob’s
- HTML to collect a file to be saved as a Blob.
<input type="file" name="theFile" id="theFile" value=" "/>
2. The Ajax call to send the selected file to the server called by say: “Upload”
var fileuploads = $("#theFile")[0]; var filename = fileuploads.files[ 0 ];
$.ajax({ url:”Upload;?size=" + filename.size, type: "POST", data: filename, processData: false, contentType: "img/jpg", success: function() { Etc etc
3. The “Upload” servlet receiving the file
String field_leng = request.getParameter("size"); int leng = Interger.parseInt( field_leng ); byte[] buffer = new byte[ leng ]; int n = 0; int m = 0; InputStream in = request.getInputStream(); while(( m = in.read( buffer, n, leng )) != -1 && leng > 0 ) { n = n + m; leng = leng - m; }
4. Saving the file as a blob to the database
// save the Blob to a data base as say, the 5th column in a PreparedStatement try { ..... prepare.setBytes( 5, buffer ); }
5. HTML ajax to retrieve back the blob from a servlet called by, say “Pic”
And displays the result in say, #pic. <img id="pic" src="./img/160x300.png" width="80" height="80" /> $.ajax({ url:”Pic;”, success: function( data ) { dataType: 'image/jpg', $("#pic").attr( "src", 'data:image/png;base64,'+data ); } });
6. The “Pic” servlet getting the Blob back from data base
Blob blob = results.getBlob( 5 ); int k = (int) blob.length(); int m = 0; int n = 0; BufferedInputStream in = new BufferedInputStream( blob.getBinaryStream()); byte[] buffer = new byte[ k ]; while(( m = in.read( buffer, n, k )) != -1 && k > 0 ) { n = n + m; k = k - m; } blob.free();
7. The “Pic” servlet sending the Blog to HTML client’s Ajax request above.
OutputStream out = null; out = response.getOutputStream(); byte[] base64 = new byte[ buffer.length ]; len = Base64.getEncoder().encode( buffer, base64 ); out.write( base64, 0, len );
8. That’s it.
© 2018, James Harry Burton. All rights reserved.