如何在android中发送带有url的图片



图像无法访问数据库

我的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/jpegrnrn"));
                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-streamrnrn");
             // "image/jpeg"
             dos.writeBytes("Content-Type: image/jpegrnrn");
             // 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();

看看这段使用php Web服务在服务器上上传图像和其他数据的代码。。。

"上载代码"按钮。。。

        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"/>

相关内容

  • 没有找到相关文章

最新更新