Sending files using POST with HttpURLConnection

前端 未结 10 1411
攒了一身酷
攒了一身酷 2020-11-22 15:45

Since the Android developers recommend to use the HttpURLConnection class, I was wondering if anyone can provide me with a good example on how to send a bitmap

10条回答
  •  再見小時候
    2020-11-22 16:40

    Here is what i did for uploading photo using post request.

    public void uploadFile(int directoryID, String filePath) {
        Bitmap bitmapOrg = BitmapFactory.decodeFile(filePath);
        ByteArrayOutputStream bao = new ByteArrayOutputStream();
    
        String upload_url = BASE_URL + UPLOAD_FILE;
        bitmapOrg.compress(Bitmap.CompressFormat.JPEG, 90, bao);
    
        byte[] data = bao.toByteArray();
    
        HttpClient httpClient = new DefaultHttpClient();
        HttpPost postRequest = new HttpPost(upload_url);
        MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    
        try {
            // Set Data and Content-type header for the image
            FileBody fb = new FileBody(new File(filePath), "image/jpeg");
            StringBody contentString = new StringBody(directoryID + "");
    
            entity.addPart("file", fb);
            entity.addPart("directory_id", contentString);
            postRequest.setEntity(entity);
    
            HttpResponse response = httpClient.execute(postRequest);
            // Read the response
            String jsonString = EntityUtils.toString(response.getEntity());
            Log.e("response after uploading file ", jsonString);
    
        } catch (Exception e) {
            Log.e("Error in uploadFile", e.getMessage());
        }
    }
    

    NOTE: This code requires libraries so Follow the instructions here in order to get the libraries.

提交回复
热议问题