0

我在 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();

            }
        }
    }
4

1 回答 1

1

上传图片或媒体文件

公共无效doFileUpload(字符串视频路径){

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

String existingFileName = videoPath;
String str = "";
System.out.println("(Talk)videoPath" + existingFileName);
String lineEnd = "\r\n";
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);
}

}

于 2015-04-09T12:32:39.787 回答