2017-01-18 1 views
1

Je suis en train de télécharger l'image en utilisant ce code:comment télécharger l'image en utilisant tableau d'octets

private String uploadFile() { 
String responseString = null; 

try { 

    HttpClient httpclient = new DefaultHttpClient(); 
    HttpPost httppost = new HttpPost(Config.FILE_UPLOAD_URL_M); 



    Log.i("UploadApp", "upload url: " + Config.FILE_UPLOAD_URL_M); 


    AndroidMultiPartEntity entity; 
    entity = new AndroidMultiPartEntity(
    new AndroidMultiPartEntity.ProgressListener() { 

    @Override 
    public void transferred(long num) { 
    // publishProgress((int) ((num/(float) totalSize) * 100)); 
    } 
    }); 

    File sourceFile; 
    sourceFile = new File(compressImage(filePath)); 

    Log.i("UploadApp", "file path: " + filePath); 

    // Adding file data to http body 

    entity.addPart("f", new FileBody(sourceFile)); //problem is here 


    entity.addPart("category", new StringBody("Bill")); 
    entity.addPart("description", new StringBody("test single")); 
    entity.addPart("file", new StringBody("unknown1")); 
    entity.addPart("clientid", new StringBody("4")); 



    totalSize = entity.getContentLength(); 
    httppost.setEntity(entity); 

    // Making server call 
    HttpResponse response = httpclient.execute(httppost); 
    HttpEntity r_entity = response.getEntity(); 

    int statusCode = response.getStatusLine().getStatusCode(); 
    if (statusCode == 200) { 
    // Server response 
    responseString = EntityUtils.toString(r_entity); 
    } else { 
    responseString = "Error occurred! Http Status Code: " + statusCode; 
    } 

} catch (ClientProtocolException e) { 
    responseString = e.toString(); 
    Log.e("UploadApp", "exception: " + responseString); 
} catch (IOException e) { 
    responseString = e.toString(); 
    Log.e("UploadApp", "exception: " + responseString); 
} 

return responseString; 

} 

J'ai un service Web pour télécharger l'image qui a 5 paramètres et 4 d'entre eux sont chaîne, mais l'un est l'octet array (byte [] f)

problème principal: comment convertir mon fichier source (image) en tableau d'octets pour télécharger l'image sur le serveur dans le code ci-dessus correspondant à ce service Web.

+1

Votre code télécharge déjà le fichier en tant que tableau d'octets. Le téléchargement normal de plusieurs parties le fait. – greenapps

Répondre

0

tout d'abord, de la source fichier, vous pouvez obtenir le chemin absolu, puis appelé méthode de téléchargement

String mCurrentPhotoPath = sourceFile.getAbsolutePath(); 


private String upload() { 
     Bitmap bm = BitmapFactory.decodeFile(mCurrentPhotoPath); 
     ByteArrayOutputStream bao = new ByteArrayOutputStream(); 
     bm.compress(Bitmap.CompressFormat.JPEG, 50, bao); 
     byte[] ba = bao.toByteArray(); 
     return Base64.encodeToString(ba, Base64.DEFAULT); 

    } 
+0

Comment appeler votre méthode ici: entity.addPart ("f", nouveau FileBody (sourceFile)) ;? –