2015-05-08 13 views
7

Sto tentando di inviare immagini codificate Base64 su un server utilizzando HttpUrlConnection. Il problema che sto avendo è che la maggior parte delle immagini viene inviata con successo, tuttavia alcuni generano un'eccezione FileNotFound. Il mio codice per la codifica dell'immagine può essere trovato sotto.Invio dell'immagine codificata Base64 al server tramite HttpUrlConnection Android

public static String encodeImage(Bitmap thumbnail) { 
      ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
      thumbnail.compress(Bitmap.CompressFormat.JPEG, 100, baos); 
      byte[] b = baos.toByteArray(); 
      String imageEncoded = Base64.encodeToString(b,Base64.URL_SAFE); 
      return imageEncoded; 
     } 

Quando cambio la linea:

String imageEncoded = Base64.encodeToString(b,Base64.URL_SAFE); 

a:

String imageEncoded = Base64.encodeToString(b,Base64.DEFAULT); 

quindi la maggior parte delle immagini generano un FileNotFoundException e un po 'viene inviato al server con successo.

sotto è il codice per il mio HttpURLConnection:

public class HttpManager { 

    public static String getData(RequestPackage p) { 

     BufferedReader reader = null; 
     String uri = p.getUri(); 
     if (p.getMethod().equals("GET")) { 
      uri += "?" + p.getEncodedParams(); 
     } 

     try { 
      URL url = new URL(uri); 
      HttpURLConnection con = (HttpURLConnection) url.openConnection(); 
      con.setRequestMethod(p.getMethod()); 


      if (p.getMethod().equals("POST")) { 
       con.setDoOutput(true); 
       OutputStreamWriter writer = new OutputStreamWriter(con.getOutputStream()); 
       writer.write(p.getEncodedParams()); //Url encoded parameters 
       writer.flush(); 
      } 

      StringBuilder sb = new StringBuilder(); 
      reader = new BufferedReader(new InputStreamReader(con.getInputStream())); 

      String line; 
      while ((line = reader.readLine()) != null) { 
       sb.append(line + "\n"); 
      } 

      return sb.toString(); 

     } catch (Exception e) { 
      e.printStackTrace(); 
      return null; 
     } finally { 
      if (reader != null) { 
       try { 
        reader.close(); 
       } catch (IOException e) { 
        e.printStackTrace(); 
        return null; 
       } 
      } 
     } 

    } 

} 

Qualsiasi aiuto sarà apprezzato. Grazie

+0

perché Base64? – pskink

+0

Provare a ridurre la bitamp se la bitmap dell'immagine è più grande. –

+0

infatti, il problema si trova sul lato server ... prolly, il server blocca richieste troppo grandi ... ancora non capisco perché non invii semplicemente binario ... – Selvin

risposta

2

Ho avuto lo stesso problema. Basta usare il codice qui sotto andrà bene:

public class MainActivity extends AppCompatActivity { 

int SELECT_PICTURE = 101; 
int CAPTURE_IMAGE = 102; 
Button getImage; 
ImageView selectedImage; 
String encodedImage; 
JSONObject jsonObject; 
JSONObject Response; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    getImage = (Button) findViewById(R.id.get_image); 
    selectedImage = (ImageView) findViewById(R.id.selected_image); 

    final AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this); 
    builder.setTitle("Profile Picture"); 
    builder.setMessage("Chooose from?"); 
    builder.setPositiveButton("GALLERY", new DialogInterface.OnClickListener() { 
     @Override 
     public void onClick(DialogInterface dialog, int which) { 
      Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI); 
      startActivityForResult(intent, SELECT_PICTURE); 
     } 
    }); 
    builder.setNegativeButton("CANCEL", null); 


} 

@Override 
protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
    // Check which request we're responding to 
    if (requestCode == SELECT_PICTURE) { 
     // Make sure the request was successful 
     Log.d("Vicky","I'm out."); 
     if (resultCode == RESULT_OK && data != null && data.getData() != null) { 
      Uri selectedImageUri = data.getData(); 
      Bitmap selectedImageBitmap = null; 
      try { 
       selectedImageBitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), selectedImageUri); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
      selectedImage.setImageBitmap(selectedImageBitmap); 
      ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); 
      selectedImageBitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream); 
      byte[] byteArrayImage = byteArrayOutputStream.toByteArray(); 
      encodedImage = Base64.encodeToString(byteArrayImage, Base64.DEFAULT); 
      Log.d("Vicky","I'm in."); 
      new UploadImages().execute(); 
     } 
    } 
} 

private class UploadImages extends AsyncTask<Void, Void, Void> { 

    @Override 
    protected void onPreExecute() { 

    } 

    @Override 
    protected Void doInBackground(Void... params) { 

     try { 
      Log.d("Vicky", "encodedImage = " + encodedImage); 
      jsonObject = new JSONObject(); 
      jsonObject.put("imageString", encodedImage); 
      jsonObject.put("imageName", "+917358513024"); 
      String data = jsonObject.toString(); 
      String yourURL = "http://54.169.88.65/events/eventmain/upload_image.php"; 
      URL url = new URL(yourURL); 
      HttpURLConnection connection = (HttpURLConnection) url.openConnection(); 
      connection.setDoOutput(true); 
      connection.setDoInput(true); 
      connection.setRequestMethod("POST"); 
      connection.setFixedLengthStreamingMode(data.getBytes().length); 
      connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8"); 
      OutputStream out = new BufferedOutputStream(connection.getOutputStream()); 
      BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, "UTF-8")); 
      writer.write(data); 
      Log.d("Vicky", "Data to php = " + data); 
      writer.flush(); 
      writer.close(); 
      out.close(); 
      connection.connect(); 

      InputStream in = new BufferedInputStream(connection.getInputStream()); 
      BufferedReader reader = new BufferedReader(new InputStreamReader(
        in, "UTF-8")); 
      StringBuilder sb = new StringBuilder(); 
      String line = null; 
      while ((line = reader.readLine()) != null) { 
       sb.append(line); 
      } 
      in.close(); 
      String result = sb.toString(); 
      Log.d("Vicky", "Response from php = " + result); 
      //Response = new JSONObject(result); 
      connection.disconnect(); 
     } catch (Exception e) { 
      Log.d("Vicky", "Error Encountered"); 
      e.printStackTrace(); 
     } 
     return null; 
    } 

    @Override 
    protected void onPostExecute(Void args) { 

    } 
    } 
} 
+0

Grazie, mi ha aiutato! – Martin

+0

@ Martin Sono contento che ti abbia aiutato. – Vicky

+0

@Martin Ma questa risposta è obsoleta, si prega di luse questo https://futurestud.io/tutorials/retrofit-2-how-to-upload-files-to-server – Vicky

1

L'alfabeto predefinito DEFAULT probabilmente contiene un '/'. In altre parole, quando si esegue Base64.encodeToString (b, Base64.DEFAULT), si finisce con '/' s nel risultato. Vorrei ricontrollare il percorso nel percorso di richiesta HTTP sul lato server.

+0

Hai ragione 'Base64.encodeToString (b, Base64.DEFAULT) 'non è sicuro per l'url. Sono venuto a saperlo di recente. – Vicky

Problemi correlati