上传图片HTTP POST的Andr​​oid

编程入门 行业动态 更新时间:2024-10-11 19:23:32
本文介绍了上传图片HTTP POST的Andr​​oid的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我在Android和有问题的android上传影像新手。我已经试图找到例子,但有没有运气:

我有错误说:

  

和这里是我的code:我已经阵列名为图像它包含了我要上传图片的路径例如/storage/sdcard0/DCIM/Camera/IMG_20131214_171438.jpg

// ONCLICK LISTENER公共OnClickListener upload_image =新OnClickListener(){            @覆盖            公共无效的onClick(视图v){                // TODO自动生成方法存根                如果(images.size()!= 0){                    。StrictMode.ThreadPolicy政策=新StrictMode.ThreadPolicy.Builder()permitAll()建();                    StrictMode.setThreadPolicy(政策);                    的for(int i = 0; I< images.size();我++){                        doFileUpload(images.get(I));                    }                }            }        };

// UPLOAD

私人无效doFileUpload(字符串upload_file){                Log.d(目前排队,upload_file);                HttpURLConnection的康恩= NULL;                DataOutputStream类DOS = NULL;                DataInputStream以inStream中= NULL;                字符串exsistingFileName = upload_file;                //这是这个地方,你做错了什么。                字符串lineEnd =\\ r \\ n;                串twoHyphens = - ;                字符串边界=acebdf13572468;                INT读取动作,方bytesAvailable,缓冲区大小;                字节[]缓冲区;                INT MAXBUFFERSIZE = 1 * 1024 * 1024;                字符串urlString =htt​​p://test.xponlm/MobileServices/api/ShipmentImages;                尝试                {                    Log.e(MediaPlayer的,内部第二种方法);                    的FileInputStream的FileInputStream =新的FileInputStream(新文件(exsistingFileName));                    网址URL =新的URL(urlString);                    康恩=(HttpURLConnection类)url.openConnection();                    conn.setDoInput(真);                    //允许输出                    conn.setDoOutput(真);                    //不要使用缓存副本。                    conn.setUseCaches(假);                    //使用POST方法。                    conn.setRequestMethod(POST);                    conn.setRequestProperty(连接,保持活动);                    conn.setRequestProperty(内容类型,的multipart / form-data的;边界=+边界);                    DOS =新的DataOutputStream类(conn.getOutputStream());                    dos.writeBytes(twoHyphens +边界+ lineEnd);                    dos.writeBytes(内容处置:表格数据;名称= \\UploadedFile的\\;文件名= \\+ exsistingFileName +\\+ lineEnd);                    dos.writeBytes(lineEnd);                    dos.writeBytes(twoHyphens +边界+ lineEnd);                    dos.writeBytes(内容处置:表格数据;名称= \\ID \\+ lineEnd);                    dos.writeBytes(lineEnd);                    dos.writeBytes(strshipmentID + lineEnd);                    dos.writeBytes(twoHyphens +边界+ lineEnd);                    dos.writeBytes(内容处置:表格数据;名称= \\将ImageType \\+ lineEnd);                    dos.writeBytes(lineEnd);                    dos.writeBytes(JPG+ lineEnd);                    dos.writeBytes(twoHyphens +边界+ lineEnd);                    dos.writeBytes(内容处置:表格数据;名称= \\文件类型\\+ lineEnd);                    dos.writeBytes(lineEnd);                    dos.writeBytes(strtype + lineEnd);                    Log.e(MediaPlayer的,头信息);                    参考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);                    在的BufferedReader =新的BufferedReader(新的InputStreamReader(conn.getInputStream()));                    串inputLine;                    而((inputLine = in.readLine())!= NULL)// tv.append(inputLine);                        Log.d(inputLine,inputLine);                    //关闭流                    Log.e(MediaPlayer的,文件写入);                    fileInputStream.close();                    dos.flush();                    dos.close();                }                赶上(MalformedURLException的前)                {                    Log.e(MediaPlayer的,ERROR1:+ ex.getMessage(),除息);                }                赶上(IOException异常IOE)                {                    Log.e(MediaPlayer的,误差2:+ ioe.getMessage(),IOE);                }                // ------------------读取服务器响应                尝试{                    inStream中=新DataInputStream所(conn.getInputStream());                    字符串str;                    而((海峡= inStream.readLine())!= NULL){                        Log.e(MediaPlayer的,服务器响应+ STR);                    }                    / *而((海峡= inStream.readLine())!= NULL){                    } * /                    inStream.close();                }                赶上(IOException异常ioex){                    Log.e(MediaPlayer的,误差3:+ ioex.getMessage(),ioex);                }            }

难道我错过了财产以后?你能告诉什么是对我的code中的问题?

解决方案

公开文件上传(字符串URL,字符串userid,            字符串文件路径,字符串状态){        HttpClient的HttpClient的=新DefaultHttpClient();        HttpPost httppost =新HttpPost(URL);        MultipartEntity实体=新MultipartEntity(                HttpMultipartMode.BROWSER_COMPATIBLE);        的HttpParams的HttpParams = httpclient.getParams();        httpParams.setIntParameter(CoreConnectionPNames.SO_TIMEOUT,100000);        尝试{            entity.addPart(键1                    新StringBody(用户ID,Charset.forName(UTF-8)));            entity.addPart(键2,                    新StringBody(状态,Charset.forName(UTF-8)));            entity.addPart(文件,新FileBody(新文件(文件路径)));            httppost.setEntity(实体);            ResponseHandler所<串GT; ResponseHandler所=新BasicResponseHandler();            字符串的响应= httpclient.execute(httppost,ResponseHandler所);        }赶上(例外五){        }    }

I'm newbie in android and having problem uploading image in android. I'd already tried to find examples but got no luck:

I am having error saying:

and here is my code: I have Array named "images" which contains the paths of images that I want to upload e.g. /storage/sdcard0/DCIM/Camera/IMG_20131214_171438.jpg

//ONCLICK LISTENER public OnClickListener upload_image = new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub if(images.size() != 0) { StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); for(int i=0; i<images.size(); i++){ doFileUpload(images.get(i)); } } } };

//UPLOAD

private void doFileUpload(String upload_file){ Log.d("Currently queued", upload_file); HttpURLConnection conn = null; DataOutputStream dos = null; DataInputStream inStream = null; String exsistingFileName = upload_file; // Is this the place are you doing something wrong. String lineEnd = "\r\n"; String twoHyphens = "--"; String boundary = "acebdf13572468"; int bytesRead, bytesAvailable, bufferSize; byte[] buffer; int maxBufferSize = 1*1024*1024; String urlString = "test.xponlm/MobileServices/api/ShipmentImages"; try { Log.e("MediaPlayer","Inside second Method"); FileInputStream fileInputStream = new FileInputStream(new File(exsistingFileName) ); URL url = new URL(urlString); conn = (HttpURLConnection) url.openConnection(); conn.setDoInput(true); // Allow Outputs conn.setDoOutput(true); // Don't use a cached copy. conn.setUseCaches(false); // Use a post method. conn.setRequestMethod("POST"); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary); dos = new DataOutputStream( conn.getOutputStream() ); dos.writeBytes(twoHyphens + boundary + lineEnd); dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + exsistingFileName +"\"" + lineEnd); dos.writeBytes(lineEnd); dos.writeBytes(twoHyphens + boundary + lineEnd); dos.writeBytes("Content-Disposition: form-data; name=\"ID\""+ lineEnd); dos.writeBytes(lineEnd); dos.writeBytes(strshipmentID + lineEnd); dos.writeBytes(twoHyphens + boundary + lineEnd); dos.writeBytes("Content-Disposition: form-data; name=\"ImageType\""+ lineEnd); dos.writeBytes(lineEnd); dos.writeBytes("JPG" + lineEnd); dos.writeBytes(twoHyphens + boundary + lineEnd); dos.writeBytes("Content-Disposition: form-data; name=\"FileType\""+ lineEnd); dos.writeBytes(lineEnd); dos.writeBytes(strtype + lineEnd); Log.e("MediaPlayer","Headers are written"); bytesAvailable = fileInputStream.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); buffer = new byte[bufferSize]; 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); BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) // tv.append(inputLine); Log.d("inputLine", inputLine); // close streams Log.e("MediaPlayer","File is written"); fileInputStream.close(); dos.flush(); dos.close(); } catch (MalformedURLException ex) { Log.e("MediaPlayer", "error1: " + ex.getMessage(), ex); } catch (IOException ioe) { Log.e("MediaPlayer", "error2: " + ioe.getMessage(), ioe); } //------------------ read the SERVER RESPONSE try { inStream = new DataInputStream ( conn.getInputStream() ); String str; while (( str = inStream.readLine()) != null) { Log.e("MediaPlayer","Server Response"+str); } /*while((str = inStream.readLine()) !=null ){ }*/ inStream.close(); } catch (IOException ioex){ Log.e("MediaPlayer", "error3: " + ioex.getMessage(), ioex); } }

Did I missed somthing? Can you tell what is the problem on my code?

解决方案

public Fileupload(String url, String userid, String filepath, String status) { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(url); MultipartEntity entity = new MultipartEntity( HttpMultipartMode.BROWSER_COMPATIBLE); HttpParams httpParams = httpclient.getParams(); httpParams.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 100000); try { entity.addPart("key 1", new StringBody(userid, Charset.forName("UTF-8"))); entity.addPart("key 2", new StringBody(status, Charset.forName("UTF-8"))); entity.addPart("File ", new FileBody(new File(filepath))); httppost.setEntity(entity); ResponseHandler<String> responseHandler = new BasicResponseHandler(); String response = httpclient.execute(httppost, responseHandler); } catch (Exception e) { } }

更多推荐

上传图片HTTP POST的Andr​​oid

本文发布于:2023-10-10 09:45:01,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1478323.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:上传图片   HTTP   POST   Andr   oid

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!