Jay Jay - 3 years ago 211
Android Question

How to upload blob to MSSQL in Android?

I'm trying to upload a jpg file into MSSQL server using JTDS 1.30 from Android Studio. I'm able to get my jpg into a blob format (or base64 if needed) using this code:

Bitmap bitmap = BitmapFactory.decodeFile("/storage/sdcard0/Shipright/Pod/test.jpg");
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, byteArrayOutputStream);
byte[] blob = byteArrayOutputStream.toByteArray();
String encodedImage = Base64.encodeToString(blob, Base64.DEFAULT);

However, the code to actually upload it into the database keeps giving me an error:

try {
Blob blobUpload = con.createBlob();
blobUpload.setBytes(0, blob);
String query = "insert into pics values ('today', 'test.jpg', '11111', 'Jay Kallen', '111', '287', '13', ?)";
PreparedStatement ps = con.prepareStatement(query);
ps.setBlob(1, blobUpload);
} catch (Exception e) {
Timber.e("error: " + e.getMessage());

I am getting an AbstractMethodError on the con.createBlob line:

09-11 10:26:46.246 8462-8462/com.procatdt.sandfile E/AndroidRuntime:
Process: com.procatdt.sandfile, PID: 8462
at com.procatdt.sandfile.CopyActivity.onCreate(CopyActivity.java:46)

It doesn't appear that I can upload it to the column directly as a base64 either, as sql server says that I need to convert it to a varbinary(max) first.

Jay Jay
Answer Source

Apparently, I didn't need to use the createblob() function to initialize the blob. I just needed to use the setBytes method of PreparedStatement, which converts a byte[] object directly to the necessary blob object. Here is the working code:

    try {
        String query = "insert into podfiles values ('09/28/2017','c:\\temp\\','" + inputFile + "', ?)";
        PreparedStatement ps = con.prepareStatement(query);
        ps.setBytes(1, blob);
    } catch (Exception e) {
        Timber.e("Blob Error: " + e.getMessage());
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download