android - 从 android 向服务器发送单个图像

标签 android

我正在尝试将单个图像发布到服务器


  • 我正在发出一个POST请求
  • 当我发出发布请求时,图像没有发送到服务器(我 检查服务器)

我尝试了什么::

MainActivity.java

public class MainActivity extends Activity {

    Button submit;
    ProgressDialog pDialog;

    ImageView imageView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        submit = (Button) findViewById(R.id.SUBMIT_BUTTON_ID);

        imageView = (ImageView) findViewById(R.id.imageView1);

        submit.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                new MainTest().execute();


            }
        });
    }




    /**
     * Method to post the image to the server.
     * U will have to change the url which will accept the image data.
     */
    private void postImageData(){

        //Some random id. u can change this based on requirements
        String newurl = "?" + "key=" + new Random().nextLong();
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://54.218.73.244:7002/Details/"+newurl);

        //Convert the bitmap drawble to a bitmap and get the string after that to send to the server
        Bitmap bitmap = ((BitmapDrawable)imageView.getDrawable()).getBitmap();
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
        byte[] bitmapdata = stream.toByteArray();
        String image_str = Base64.encodeToString(bitmapdata, Base64.DEFAULT);

        try {
            // Add your data
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
            nameValuePairs.add(new BasicNameValuePair("imageData", image_str));
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

            // Execute HTTP Post Request
            HttpResponse response = httpclient.execute(httppost);
            Log.v("Response", response.toString());

        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
        } catch (IOException e) {
            // TODO Auto-generated catch block
        }

    }

    public class MainTest extends AsyncTask<String, Integer, String> {

        @Override
        protected void onPreExecute() {
            pDialog = new ProgressDialog(MainActivity.this);
            pDialog.setMessage("Loading..");
            pDialog.setIndeterminate(true);
            pDialog.setCancelable(false);
            pDialog.show();
        }

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

            postImageData();

            return null;
        }

        @Override
        protected void onPostExecute(String result) {
            // TODO Auto-generated method stub

            super.onPostExecute(result);
            // data=jobj.toString();
            pDialog.dismiss();

        }

    }

}

我该如何解决这个问题


[编辑]

我检查了服务器是否正常运行以接受图像,但它看起来运行良好!当使用 postman-tool 检查上传图片时,所以问题必须是客户端部分

MainActivity.java

public class MainActivity extends Activity {

    Button submit;
    ProgressDialog pDialog;

    ImageView imageView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        submit = (Button) findViewById(R.id.SUBMIT_BUTTON_ID);

        imageView = (ImageView) findViewById(R.id.imageView1);

        submit.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                new MainTest().execute();


            }
        });
    }



    /**
     * Method to post the image to the server.
     * U will have to change the url which will accept the image data.
     * @throws IOException 
     */
    public void postImageData() throws IOException
    {
         //Some random id. u can change this based on requirements
        String newurl = "?" + "key=" + new Random().nextLong();
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://54.218.73.244:7002/Details/"+newurl);

        //Convert the bitmap drawble to a bitmap and get the string after that to send to the server
        Bitmap bitmap = ((BitmapDrawable)imageView.getDrawable()).getBitmap();
        String dir = Environment.getExternalStorageDirectory().toString();
        OutputStream fos = null;

        File file = new File(dir,"temp.JPEG");
        fos = new FileOutputStream(file);
        BufferedOutputStream bos = new BufferedOutputStream(fos);
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);

        bos.flush();
        bos.close();

        MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

        File mFile = new File(dir, "temp.JPEG");
        FileBody encFile = new FileBody(mFile,"image/jpeg");
        entity.addPart("images", encFile);
        //Another key/value parameter
        //entity.addPart("UserId", new StringBody(userId)); 

        httppost.setEntity(entity);

        HttpClient client = new DefaultHttpClient();
        HttpResponse response = httpclient.execute(httppost);                

        String data = EntityUtils.toString(response.getEntity());
        System.out.println("response data:"+data);
    }

    public class MainTest extends AsyncTask<String, Integer, String> {

        @Override
        protected void onPreExecute() {
            pDialog = new ProgressDialog(MainActivity.this);
            pDialog.setMessage("Loading..");
            pDialog.setIndeterminate(true);
            pDialog.setCancelable(false);
            pDialog.show();
        }

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

            try {
                postImageData();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            return null;
        }

        @Override
        protected void onPostExecute(String result) {
            // TODO Auto-generated method stub

            super.onPostExecute(result);
            // data=jobj.toString();
            pDialog.dismiss();

        }

    }

}

最佳答案

你必须使用MultipartEntity 上传图片到服务器

  public void postImageData()
    {
         //Some random id. u can change this based on requirements
        String newurl = "?" + "key=" + new Random().nextLong();
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://54.218.73.244:7002/Details/"+newurl);

        //Convert the bitmap drawble to a bitmap and get the string after that to send to the server
        Bitmap bitmap = ((BitmapDrawable)imageView.getDrawable()).getBitmap();
        String dir = Environment.getExternalStorageDirectory().toString();
        OutputStream fos = null;

        File file = new File(dir,"temp.JPEG");
        fos = new FileOutputStream(file);
        BufferedOutputStream bos = new BufferedOutputStream(fos);
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);

        bos.flush();
        bos.close();

        MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

        File mFile = new File(dir, "temp.JPEG");
        FileBody encFile = new FileBody(mFile,"image/jpeg");
        entity.addPart("images", encFile);
        //Another key/value parameter
        //entity.addPart("UserId", new StringBody(userId)); 

        httppost.setEntity(entity);

        HttpClient client = new DefaultHttpClient();
        HttpResponse response = httpclient.execute(httppost);                

        String data = EntityUtils.toString(response.getEntity());
        System.out.println("response data:"+data);
    }

关于android - 从 android 向服务器发送单个图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20391766/

相关文章:

android - 在 Android 中为按钮组应用样式

android - Viewpager 初始 fragment 中的操作项未显示

android - 动态主题和自定义样式

java - 所有 Activity 中都可用的选项菜单

android - 如何在android 2.2中发送消息?

AndroidThreeTen 在没有 robolectric 的情况下无法在单元测试中工作?

android - 使用 y 坐标确定 ListView 项目在 ListView 中的位置

android - Android 4.4 KitKat 上的 SMS 实用程序

android - 如何从android中simplecursoradapter中的[]值拆分

android - Android Instant Apps:YouTube Android Player不兼容吗?