如何发送图像在Android的网址图像、网址、Android

由网友(痣梇)分享简介:图像无法达到数据库我的doInBackground()方法。 {尝试            文件文件名=新的文件(/存储/ sdcard1 /接收/ IAF-Sarang.jpg);            DefaultHttpClient mHttpClient;            比肩的HttpParams...

图像无法达到数据库

我的doInBackground()方法。

  {尝试            文件文件名=新的文件(/存储/ sdcard1 /接收/ IAF-Sarang.jpg);            DefaultHttpClient mHttpClient;            比肩的HttpParams =新BasicHttpParams();            par.setParameter(CoreProtocolPNames.PROTOCOL_VERSION,HttpVersion.HTTP_1_1);            mHttpClient =新DefaultHttpClient(PAR);            尝试{                HttpPost httppost =新HttpPost(http://www.hugosys.in/www.nett-torg.no/api/rpcs/uploadfiles/?);                MultipartEntity multipartEntity =新MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);                multipartEntity.addPart(POST_ID,新StringBody(1368));                multipartEntity.addPart(user_ID的新StringBody(62));                multipartEntity.addPart(文件,新FileBody(FILE_NAME,内容类型:image / JPEG  r  n  r  n));                httppost.setEntity(multipartEntity);                mHttpClient.execute(httppost,新PhotoUploadResponseHandler());            }赶上(例外五){               e.printStackTrace();               的System.out.println(+ E);            }        }赶上(例外五){            // TODO自动生成catch块            e.printStackTrace();        }        返回response_string; 

下面是PhotoUploadResponseHandler类

 私有类PhotoUploadResponseHandler实现ResponseHandler所<对象> {    @覆盖    公共对象用handleResponse(HTT presponse响应)            抛出ClientProtocolException,IOException异常{        HttpEntity r_entity = response.getEntity();        字符串RSTRING = EntityUtils.toString(r_entity);        Log.d(UPLOAD,RSTRING);        response_string = RSTRING;        返回RSTRING;    }} 

有是无法触及code的一个多块,我已经试过,但在POST_ID

图片被张贴成功地

  //打开一个URL连接到这个Servlet             的FileInputStream的FileInputStream =新的FileInputStream(的资源文件);             网址URL =新的URL(http://www.hugosys.in/www.nett-torg.no/api/rpcs/uploadfiles/?);             //打开HTTP连接的URL             康恩=(HttpURLConnection类)url.openConnection();             conn.setDoInput(真); //允许输入             conn.setDoOutput(真); //允许输出             conn.setUseCaches(假); //不要使用缓存副本             conn.setRequestMethod(POST);             conn.setRequestProperty(连接,保持活动);             conn.setRequestProperty(ENCTYPE,多部分/表单数据);             conn.setRequestProperty(内容类型,的multipart / form-data的;边界=+边界);             conn.setRequestProperty(POST_ID,1368);             conn.setRequestProperty(USER_ID,62);             conn.setRequestProperty(文件FILE_NAME);             DOS =新的DataOutputStream类(conn.getOutputStream());             dos.writeBytes(twoHyphens +边界+ lineEnd);             dos.writeBytes(内容处置:表格数据;名称=文件[];文件名=+ FILE_NAME ++ lineEnd);             //dos.writeBytes("Content-Type:应用程序/八位字节流 r  n  r  n);             //图像/ JPEG             dos.writeBytes(内容类型:image / JPEG  r  n  r  n);             //创建最大大小的缓冲区             参考bytesAvailable = fileInputStream.available();             BUFFERSIZE = Math.min(方bytesAvailable,MAXBUFFERSIZE);             缓冲区=新的字节[缓冲区大小]             //读取文件,并将其写入形式...             读取动作= fileInputStream.read(缓冲液,0,缓冲区大小);             而(读取动作大于0){               dos.write(缓冲液,0,缓冲区大小);               参考bytesAvailable = fileInputStream.available();               BUFFERSIZE = Math.min(方bytesAvailable,MAXBUFFERSIZE);               读取动作= fileInputStream.read(缓冲液,0,缓冲区大小);              }             dos.writeBytes(lineEnd);             dos.writeBytes(twoHyphens +边界+ twoHyphens + lineEnd);             //发送文件数据后necesssary多部分的表单数据...             //服务器的响应(code和消息)            INT serverResponse code = conn.getResponse code();            serverResponseMessage = conn.getResponseMessage();            是= conn.getInputStream();             Log.i(一个UploadFile,HTTP响应是:+ serverResponseMessage +:+ serverResponse code);             InputStreamReader的InputStreamReader的=新的InputStreamReader(是);             的BufferedReader的BufferedReader =新的BufferedReader(InputStreamReader的);             字符串bufferedStrChunk = NULL;             而((bufferedStrChunk = bufferedReader.readLine())!= NULL){                 stringBuilder.append(bufferedStrChunk);             }             //关闭流//             fileInputStream.close();             dos.flush();             dos.close(); 
android 自动上传手机图库,将iCloud照片传输到Android的3种方法

解决方案

有看这code为使用PHP服务器与其他数据上传图像的WebServices ...

code对于上传按钮...

 上传=(按钮)findViewById(R.id.button1);        upload.setOnClickListener(新View.OnClickListener(){            公共无效的onClick(视图v){                位= BitmapFactory.de codeResource(getResources(),R.drawable.img);                新ImageUploadTask()执行();            }        }); 

这是异步任务上传图片与服务器的数据...

 类ImageUploadTask扩展的AsyncTask<太虚,太虚,字符串> {        私人StringBuilder的S;        @覆盖        在preExecute保护无效(){            // TODO自动生成方法存根            super.on preExecute();            mProgress =新ProgressDialog(MainActivity.this);            mProgress.setMessage(加载);            mProgress.setProgressStyle(ProgressDialog.STYLE_SPINNER);            mProgress.setCancelable(假);            mProgress.show();        }        @覆盖        保护字符串doInBackground(虚空...... unsued){            尝试{                串sResponse =;                字符串URL =htt​​p://www.hugosys.in/www.nett-torg.no/api/rpcs/uploadfiles/?                HttpClient的HttpClient的=新DefaultHttpClient();                HttpPost httpPost =新HttpPost(URL);                MultipartEntity实体=新MultipartEntity();                ByteArrayOutputStream BOS =新ByteArrayOutputStream();                bitmap.com preSS(比较pressFormat.JPEG,100,BOS);                字节[]数据= bos.toByteArray();                entity.addPart(POST_ID,新StringBody(1368));                entity.addPart(user_ID的新StringBody(62));                entity.addPart(文件[],新ByteArrayBody(数据,图像/ JPEG,test2.jpg));                httpPost.setEntity(实体);                HTT presponse响应= httpClient.execute(httpPost);                的BufferedReader读者=新的BufferedReader(新的InputStreamReader(response.getEntity()的getContent(),UTF-8)。);                S =新的StringBuilder();                而((sResponse = reader.readLine())!= NULL)                {                    S = s.append(sResponse);                }                如果(response.getStatusLine()的getStatus code()== HttpStatus.SC_OK)                {                    返回s.toString();                }其他                {                    回归{状态:假,消息:出现了错误};                }            }赶上(例外五){                Toast.makeText(getApplicationContext(),e.​​getMessage(),Toast.LENGTH_LONG).show();                返回null;            }        }        @覆盖        保护无效onPostExecute(字符串sResponse){            尝试{                mProgress.dismiss();                如果(sResponse!= NULL){                    Toast.makeText(getApplicationContext(),sResponse +照片上传成功,Toast.LENGTH_SHORT).show();                }            }赶上(例外五){                Toast.makeText(getApplicationContext(),e.​​getMessage(),                        Toast.LENGTH_LONG).show();                Log.e(e.getClass()的getName(),e.​​getMessage(),E。);            }        }    } 

添加权限中的Manifest.xml ..

 <使用许可权的android:NAME =android.permission.INTERNET对/> 

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

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

解决方案

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

阅读全文

相关推荐

最新文章