How to send image with url in android

2019-06-14 12:22发布

Image is not able to reach on database

my doInBackground() method

try {

            File file_name=new File("/storage/sdcard1/Received/IAF-Sarang.jpg");
            DefaultHttpClient mHttpClient;
            HttpParams par = new BasicHttpParams();
            par.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
            mHttpClient = new DefaultHttpClient(par);

            try {

                HttpPost httppost = new HttpPost("http://www.hugosys.in/www.nett-torg.no/api/rpcs/uploadfiles/?");
                MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);                    
                multipartEntity.addPart("post_id", new StringBody("1368"));
                multipartEntity.addPart("user_id", new StringBody("62"));
                multipartEntity.addPart("files", new FileBody(file_name, "Content-Type: image/jpeg\r\n\r\n"));
                httppost.setEntity(multipartEntity);
                mHttpClient.execute(httppost, new PhotoUploadResponseHandler());

            } catch (Exception e) {
               e.printStackTrace();
               System.out.println(""+e);
            }

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

Here is the PhotoUploadResponseHandler class

    private class PhotoUploadResponseHandler implements ResponseHandler<Object> {

    @Override
    public Object handleResponse(HttpResponse response)
            throws ClientProtocolException, IOException {

        HttpEntity r_entity = response.getEntity();
        String rString = EntityUtils.toString(r_entity);
        Log.d("UPLOAD", rString);
        response_string=rString;
        return rString;
    }

}

There is one more block of code which i have tried but in that post_id is not reached

Image was posted sucessfully

              // open a URL connection to the Servlet
             FileInputStream fileInputStream = new FileInputStream(sourceFile);
             URL url = new URL("http://www.hugosys.in/www.nett-torg.no/api/rpcs/uploadfiles/?");

             // Open a HTTP  connection to  the URL
             conn = (HttpURLConnection) url.openConnection();
             conn.setDoInput(true); // Allow Inputs
             conn.setDoOutput(true); // Allow Outputs
             conn.setUseCaches(false); // Don't use a Cached Copy
             conn.setRequestMethod("POST");
             conn.setRequestProperty("Connection", "Keep-Alive");
             conn.setRequestProperty("ENCTYPE", "multipart/form-data");
             conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);
             conn.setRequestProperty("post_id", "1368");
             conn.setRequestProperty("user_id", "62");
             conn.setRequestProperty("files", file_name);                 
             dos = new DataOutputStream(conn.getOutputStream());                
             dos.writeBytes(twoHyphens + boundary + lineEnd);
             dos.writeBytes("Content-Disposition: form-data;name=files[];filename="+file_name+""+ lineEnd);
             //dos.writeBytes("Content-Type: application/octet-stream\r\n\r\n");
             // "image/jpeg"
             dos.writeBytes("Content-Type: image/jpeg\r\n\r\n");
             // 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); 

              }

             dos.writeBytes(lineEnd);
             dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

             // send multipart form data necesssary after file data...

             // Responses from the server (code and message)
            int serverResponseCode = conn.getResponseCode();
            serverResponseMessage = conn.getResponseMessage();
            is=conn.getInputStream();

             Log.i("uploadFile", "HTTP Response is : "+ serverResponseMessage + ": " + serverResponseCode);

             InputStreamReader inputStreamReader = new InputStreamReader(is);
             BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

             String bufferedStrChunk = null;

             while((bufferedStrChunk = bufferedReader.readLine()) != null){
                 stringBuilder.append(bufferedStrChunk);
             }
             //close the streams //
             fileInputStream.close();
             dos.flush();
             dos.close();

1条回答
Deceive 欺骗
2楼-- · 2019-06-14 12:40

Have look This code for uploading image with other data on server using php webservices...

Code For Upload Button...

        upload = (Button) findViewById(R.id.button1);
        upload.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                bitmap= BitmapFactory.decodeResource(getResources(), R.drawable.img);
                new ImageUploadTask().execute();
            }
        });

This is async task to upload image with data on server...

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

        @Override
        protected void onPreExecute() {
            // TODO Auto-generated method stub
            super.onPreExecute();
            mProgress = new ProgressDialog(MainActivity.this);
            mProgress.setMessage("Loading");
            mProgress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            mProgress.setCancelable(false);
            mProgress.show();
        }
        @Override
        protected String doInBackground(Void... unsued) {
            try {
                String sResponse = "";
                String url = "http://www.hugosys.in/www.nett-torg.no/api/rpcs/uploadfiles/?";
                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("post_id", new StringBody("1368"));
                entity.addPart("user_id", new StringBody("62"));
                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();
                return null;
            }
        }

        @Override
        protected void onPostExecute(String sResponse) {
            try {
                mProgress.dismiss();
                if (sResponse != null) {
                    Toast.makeText(getApplicationContext(), sResponse + " Photo uploaded successfully",Toast.LENGTH_SHORT).show();
                }
            } catch (Exception e) {
                Toast.makeText(getApplicationContext(), e.getMessage(),
                        Toast.LENGTH_LONG).show();
                Log.e(e.getClass().getName(), e.getMessage(), e);
            }
        }
    }

Add Permission in Manifest.xml..

 <uses-permission android:name="android.permission.INTERNET"/>
查看更多
登录 后发表回答