【问题标题】:How to send image with url in android如何在android中发送带有url的图像
【发布时间】:2014-05-28 09:33:07
【问题描述】:

图片无法访问数据库

我的 doInBackground() 方法

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;

这是 PhotoUploadResponseHandler 类

    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;
    }

}

我已经尝试了另外一个代码块,但没有达到 post_id

图片发布成功

              // 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();

【问题讨论】:

  • 您可能想要更好地解释实际问题。使用一小段代码来解释你在做什么,而不是转储你的代码,看看这个sscce.org。还要尝试解释代码的预期内容以及实际发生的情况。

标签: android image file multipartform-data


【解决方案1】:

看看这个使用php webservices在服务器上上传图像和其他数据的代码......

上传按钮的代码...

        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();
            }
        });

这是在服务器上上传带有数据的图像的异步任务...

    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);
            }
        }
    }

在 Manifest.xml 中添加权限..

 <uses-permission android:name="android.permission.INTERNET"/>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-08
    • 2019-06-21
    • 2016-03-24
    相关资源
    最近更新 更多