Невозможно загрузить изображение на сервер в Android

#android #bitmap #image-uploading #multipartform-data #multipartentity

#Android #растровое изображение #загрузка изображения #multipartform-данные #multipartentity

Вопрос:

Я создал действие формы в Android, которое содержит некоторые текстовые поля и фотографию, я хочу отправить эти параметры на сервер

Я могу успешно загрузить все остальные параметры, но изображение не загружается на сервер, пожалуйста, помогите мне спасти меня .. Спасибо, мой код выглядит следующим образом: код

 Bitmap bitmap;
onClick(){
    editEnable();
            System.out.println("::::::::::save clicked:::::::::");
            header.edit.setVisibility(View.GONE);
            bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
            // new EditProfileAPI().execute();
            new ImageUploadTask().execute();

            // Profile Edit Call...!!!

            break;
}
    class ImageUploadTask extends AsyncTask<Void, Void, String> {
        private StringBuilder s;

        @Override
        protected void onPreExecute() {
            // TODO Auto-generated method stub
            super.onPreExecute();

            pDialog = new ProgressDialog(HomeActivity.this);
            pDialog.setMessage("Loading");
            pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            pDialog.setCancelable(false);
            pDialog.show();
        }

        @Override
        protected String doInBackground(Void... unsued) {
            try {
                String sResponse = "";
                String url = Const.API_eDIT_PROFILE   "?";
                HttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(url);
                MultipartEntity entity = new MultipartEntity();

                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                bitmap.compress(CompressFormat.JPEG, 100, bos);
                byte[] data = bos.toByteArray();
                entity.addPart("customer_id", new StringBody(Pref.getValue(HomeActivity.this, Const.PREF_CUSTOMER_ID, "")));
                entity.addPart("first_name", new StringBody(et_firstname.getText().toString().trim()));
                entity.addPart("last_name", new StringBody(et_lastname.getText().toString().trim()));
                entity.addPart("customer_add", new StringBody(tv_adres.getText().toString().trim()));
                entity.addPart("customer_phone", new StringBody(tv_phone.getText().toString().trim()));
                entity.addPart("business_info", new StringBody(tv_busines.getText().toString().trim()));
                entity.addPart("business_type", new StringBody(tv_busines_typ.getText().toString().trim()));
                entity.addPart("bank_ac", new StringBody(tv_bank_acnt.getText().toString().trim()));
                entity.addPart("dr_cr_card", new StringBody(tv_card.getText().toString().trim()));
                entity.addPart("purpose_code", new StringBody(et_purpose_code.getText().toString().trim()));
                entity.addPart("paypal_email", new StringBody(tv_paypal_email.getText().toString().trim()));
                entity.addPart("password", new StringBody(et_fpassword.getText().toString().trim()));
                entity.addPart("filename", new StringBody("test2.jpg"));

                entity.addPart("files[]", new ByteArrayBody(data, "image/jpeg", "test2.jpg"));

                httpPost.setEntity(entity);
                HttpResponse response = httpClient.execute(httpPost);

                BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));

                s = new StringBuilder();

                while ((sResponse = reader.readLine()) != null) {
                    s = s.append(sResponse);
                }

                if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                    return s.toString();
                } else {
                    return "{"status":"false","message":"Some error occurred"}";
                }
            } catch (Exception e) {
                Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
                System.out.println("::::::::::::::::::::::::::::MY exception in edit::::::::::::::::"   e.getMessage());
                return null;
            }
        }

        @Override
        protected void onPostExecute(String sResponse) {
            try {
                pDialog.dismiss();
                if (sResponse != null) {
                    Toast.makeText(getApplicationContext(), sResponse   " Photo uploaded successfully", Toast.LENGTH_SHORT).show();
                    System.out.println("::::::::::::::::::::::::::::MY SUCCESS RESPONESE in edit::::::::::::::::"   sResponse);
                }
            } catch (Exception e) {
                Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();

            }
        }
    }
  

Комментарии:

1. Попробуйте использовать FileBody вместо ByteArrayBody.

2. @Haresh-извините, не могли бы вы, пожалуйста, дать мне какой-нибудь пример кода .. пожалуйста.. tahnks

3. Попробуйте так: entity.AddPart(«imagekey», new FileBody(новый файл («imagepath»), «MimeTypeOfImage»));

4. могу ли я поместить изображение в формате drwable?]

5. Да, вам нужно его найти.

Ответ №1:

Загрузить изображение или медиафайл

public void doFileUpload(String videoPath) {

 HttpURLConnection conn = null;
DataOutputStream dos = null;
DataInputStream inStream = null;

String existingFileName = videoPath;
String str = "";
System.out.println("(Talk)videoPath"   existingFileName);
String lineEnd = "rn";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 10  1024  1024;

try {
 // ------------------ CLIENT REQUEST
 FileInputStream fileInputStream = new FileInputStream(new File(
   existingFileName));
 // open a URL connection to the Servlet
 URL url = new URL(url1);
 // Open a HTTP connection to the URL
 conn = (HttpURLConnection) url.openConnection();
 // Allow Inputs
 conn.setDoInput(true);
 // Allow Outputs
 conn.setDoOutput(true);
 // Don't use a cached copy.
 conn.setUseCaches(false);
 // Use a post method.
 conn.setRequestMethod("POST");
 conn.setRequestProperty("Connection", "Keep-Alive");
 conn.setRequestProperty("Content-Type",
   "multipart/form-data;boundary="   boundary);
 dos = new DataOutputStream(conn.getOutputStream());
 dos.writeBytes(twoHyphens   boundary   lineEnd);
 dos.writeBytes("Content-Disposition: form-data; name="uploadedfile";filename=""
     existingFileName   """   lineEnd);
 dos.writeBytes(lineEnd);
 // create a buffer of maximum size
 bytesAvailable = fileInputStream.available();
 bufferSize = Math.min(bytesAvailable, maxBufferSize);
 buffer = new byte[bufferSize];
 // read file and write it into form...
 bytesRead = fileInputStream.read(buffer, 0, bufferSize);
 while (bytesRead > 0) {
  dos.write(buffer, 0, bufferSize);
  bytesAvailable = fileInputStream.available();
  bufferSize = Math.min(bytesAvailable, maxBufferSize);
  bytesRead = fileInputStream.read(buffer, 0, bufferSize);
 }
 // send multipart form data necesssary after file data...
 dos.writeBytes(lineEnd);
 dos.writeBytes(twoHyphens   boundary   twoHyphens   lineEnd);
 // close streams
 Log.e("Debug", "File is written");
 fileInputStream.close();
 dos.flush();
 dos.close();
} catch (MalformedURLException ex) {
 Log.e("Debug", "error: "   ex.getMessage(), ex);
} catch (IOException ioe) {
 Log.e("Debug", "error: "   ioe.getMessage(), ioe);
}
// ------------------ read the SERVER RESPONSE
try {
 inStream = new DataInputStream(conn.getInputStream());

 while ((str = inStream.readLine()) != null) {
  Log.e("Debug", "Server Response "   str);

 }
 inStream.close();
} catch (IOException ioex) {
 Log.e("Debug", "error: "   ioex.getMessage(), ioex);
}
  

}