Not able to upload image to server using Httpreque

2019-03-06 11:14发布

问题:

I have created an app in which user select an image from gallery and that image is uploaded to the server.I tried doing it using Httprequest Library.But i m not being able to upload it.

Code

HttpRequest request = HttpRequest.post ("https://beta135.hamarisuraksha.com/Web/MobileApp/PostImsafePrflPic.aspx").send ("MODE=PP" + "&ID=" + "8" + "&ext=.jpg" + f);
            request.part ("mode", "MODE=PP");
            request.part ("id", "&ID=34588A34-E969-4723-84FE-E5409B66A5B7");
            request.part ("ext", "&ext=.jpg");
            request.part ("file", f);
            String response = request.body ();
            Log.e ("Image Upload", "" + response);


            return response; 

Also if there is any other good library which i can use to do this work,plz lemme know.

回答1:

Try This code and this library add httpmime-4.1-beta1.jar :

String url = "Your Url";


            HttpClient client = new DefaultHttpClient();
            client.getParams().setParameter(
                    CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
            HttpPost postMethod = new HttpPost(url);


            MultipartEntity entity = new MultipartEntity();

              entity.addPart("fname", new StringBody("xyz"));

            try {

                    File file1 = new File("Your image Path");
                    FileBody bin1 = new FileBody(file1, "images/jpeg");

                    entity.addPart("file", bin1);

                postMethod.setEntity(entity);
                HttpResponse response;
                response = client.execute(postMethod);

                String result = EntityUtils.toString(response.getEntity());

            }

            catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }