问题描述
我完全迷失了,我试图通过Android应用将照片发送到PHP网页.
理论上一切都应该正确,但是目的地数据已损坏或我不知道的东西...
我可以获取帖子数据,我尝试了一个简单的字符串,它工作正常,但是有一个重量文件,数据似乎损坏了.
public class EncodingAndSending extends Thread{ ShareOnMyWebSiteActivity mycontext; ContentResolver cr; Uri uri; public Handler mainHandler,sHandler; public EncodingAndSending(ShareOnMyWebSiteActivity myctxt,Handler mainone,Uri URI,ContentResolver crr){ mycontext=myctxt; cr=crr; uri=URI; mainHandler=mainone; this.start(); } return buffer.toString().toUpperCase(); } public void run(){ InputStream is=null; byte[] data=null; try { is = cr.openInputStream(uri); // Get binary bytes for encode data = getFileBytes(is); } catch (Exception e1) { // TODO Auto-generated catch block e1.printStackTrace(); } String data_string=Base64.encodeToString(data,Base64.URL_SAFE); if(data_string!=""){ SendRequest(data_string); } else{ } } public byte[] getFileBytes(InputStream ios) throws IOException { ByteArrayOutputStream ous = null; //InputStream ios = null; try { byte[] buffer = new byte[4096]; ous = new ByteArrayOutputStream(); //ios = new FileInputStream(file); int read = 0; while ((read = ios.read(buffer)) != -1) ous.write(buffer, 0, read); } finally { try { if (ous != null) ous.close(); } catch (IOException e) { // swallow, since not that important } try { if (ios != null) ios.close(); } catch (IOException e) { // swallow, since not that important } } return ous.toByteArray(); } private void SendRequest(String data_string){ HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("xxxxx.php"); try { List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); nameValuePairs.add(new BasicNameValuePair("image", data_string)); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); // Execute HTTP Post Request HttpResponse response = httpclient.execute(httppost); ResponseHandler<String> responseHandler=new BasicResponseHandler(); String responseBody = httpclient.execute(httppost, responseHandler); } catch (Exception e) { // TODO Auto-generated catch block } } }
编辑:
这有效.我可以编码,解码和预览图像.我没有使用getBytes()函数,我不知道问题是否来自那里.
我会告诉你.
super.onCreate(savedInstanceState); setContentView(R.layout.test_image); ImageView image = (ImageView) findViewById(R.id.imageView1); FileInputStream in; BufferedInputStream buf; Intent intent = getIntent(); Bundle extras = intent.getExtras(); Uri uri = (Uri) extras.getParcelable(Intent.EXTRA_STREAM); ContentResolver cr = getContentResolver(); Bitmap bMap=null; try { InputStream is = cr.openInputStream(uri); bMap = BitmapFactory.decodeStream(is); if (is != null) { is.close(); } } catch (Exception e) { Log.e("Error reading file", e.toString()); } ByteArrayOutputStream baos = new ByteArrayOutputStream(); bMap.compress(Bitmap.CompressFormat.JPEG, 100, baos); byte[] b = baos.toByteArray(); String data_string=Base64.encodeToString(b,Base64.DEFAULT); b=null;bMap=null; b=Base64.decode(data_string, Base64.DEFAULT); bMap=BitmapFactory.decodeByteArray(b, 0, b.length); image.setImageBitmap(bMap);
推荐答案
我写了一个小应用程序,该应用程序允许将手机相机拍摄的图像发送到数据库.这是我解决问题的方式...
public void writeCommentForRestaurant(int id, String comment, String author, Bitmap image) { if (image != null) { /* Get the image as string */ // Normal ByteArrayOutputStream full_stream = new ByteArrayOutputStream(); image.compress(Bitmap.CompressFormat.PNG, 100, full_stream); byte[] full_bytes = full_stream.toByteArray(); String img_full = Base64.encodeToString(full_bytes, Base64.DEFAULT); // Thumbnail ByteArrayOutputStream thumb_stream = new ByteArrayOutputStream(); // The getScaledBitmap method only minimizes the Bitmap to a small icon! getScaledBitmap(image, 72).compress(Bitmap.CompressFormat.JPEG, 75, thumb_stream); byte[] thumb_bytes = thumb_stream.toByteArray(); String img_thumbnail = Base64.encodeToString(thumb_bytes, Base64.DEFAULT); // new HTTPWorker(ctx, mHandler, HTTPWorker.WRITE_COMMENT, true).execute( // Integer.toString(id), comment, author, img_thumbnail, img_full); } else { // new HTTPWorker(ctx, mHandler, HTTPWorker.WRITE_COMMENT, true).execute( // Integer.toString(id), comment, author, null, null); } }
httpworker只是一个构造httpmethod的异步.
... /* Add arguments */ arguments.add(new BasicNameValuePair("idrestaurant", params[0])); arguments.add(new BasicNameValuePair("comment", params[1])); arguments.add(new BasicNameValuePair("author", params[2])); if (params.length > 3) { arguments.add(new BasicNameValuePair("image", params[3])); arguments.add(new BasicNameValuePair("bigimage", params[4])); } ...
然后我将其发送到服务器.
/** * Executes a httppost to a server instance with the given POST arguments * and returns a String response from the server. */ private String httppost(String url, ArrayList<NameValuePair> args) { /* Create the channel for communicaton */ InputStream is = null; /* Send request to server */ try { /* Create the POST */ HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(url); /* Add the login information "POST" variables in the php */ httppost.setEntity(new UrlEncodedFormEntity(args)); /* Execute the http POST and get the response */ HttpResponse response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); is = entity.getContent(); } catch (Exception e) { Log.e(TAG, "Error in http connection " + e.toString()); return null; } /* Read response from server */ try { /* Read the response stream */ BufferedReader reader = new BufferedReader(new InputStreamReader( is, "iso-8859-1"), 8); /* Copy the response to StringBuilder */ StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } is.close(); /* Return the response as string */ return sb.toString(); } catch (Exception e) { Log.e(TAG, "Error converting result " + e.toString()); return null; } }
其他推荐答案
很好,谢谢.实际上,问题来自服务器. BASE64被发送到PHP脚本,该脚本将字符串存储到字段中...这是长篇小说类型(MySQL).问题是损坏数据,我将其更改为blob,它运行良好.不是吗?
非常感谢您的帮助.
我的第一个主题和一个很棒的社区在这里很棒.
稍后再见.
问题描述
I am completely lost, I am trying to send a photo via an android app to a php webpage.
Theoritically everything should be right but the destination data is corrupted or something I don't know...
I can get the post data, I tried with a simple string it worked fine but with a heavy file the data seems corrupted.
public class EncodingAndSending extends Thread{ ShareOnMyWebSiteActivity mycontext; ContentResolver cr; Uri uri; public Handler mainHandler,sHandler; public EncodingAndSending(ShareOnMyWebSiteActivity myctxt,Handler mainone,Uri URI,ContentResolver crr){ mycontext=myctxt; cr=crr; uri=URI; mainHandler=mainone; this.start(); } return buffer.toString().toUpperCase(); } public void run(){ InputStream is=null; byte[] data=null; try { is = cr.openInputStream(uri); // Get binary bytes for encode data = getFileBytes(is); } catch (Exception e1) { // TODO Auto-generated catch block e1.printStackTrace(); } String data_string=Base64.encodeToString(data,Base64.URL_SAFE); if(data_string!=""){ SendRequest(data_string); } else{ } } public byte[] getFileBytes(InputStream ios) throws IOException { ByteArrayOutputStream ous = null; //InputStream ios = null; try { byte[] buffer = new byte[4096]; ous = new ByteArrayOutputStream(); //ios = new FileInputStream(file); int read = 0; while ((read = ios.read(buffer)) != -1) ous.write(buffer, 0, read); } finally { try { if (ous != null) ous.close(); } catch (IOException e) { // swallow, since not that important } try { if (ios != null) ios.close(); } catch (IOException e) { // swallow, since not that important } } return ous.toByteArray(); } private void SendRequest(String data_string){ HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("xxxxx.php"); try { List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); nameValuePairs.add(new BasicNameValuePair("image", data_string)); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); // Execute HTTP Post Request HttpResponse response = httpclient.execute(httppost); ResponseHandler<String> responseHandler=new BasicResponseHandler(); String responseBody = httpclient.execute(httppost, responseHandler); } catch (Exception e) { // TODO Auto-generated catch block } } }
EDIT:
This works. I can encode and decode and preview the image. I didn't use the getBytes() function I don't know if the problem comes from there.
I'll let you know.
super.onCreate(savedInstanceState); setContentView(R.layout.test_image); ImageView image = (ImageView) findViewById(R.id.imageView1); FileInputStream in; BufferedInputStream buf; Intent intent = getIntent(); Bundle extras = intent.getExtras(); Uri uri = (Uri) extras.getParcelable(Intent.EXTRA_STREAM); ContentResolver cr = getContentResolver(); Bitmap bMap=null; try { InputStream is = cr.openInputStream(uri); bMap = BitmapFactory.decodeStream(is); if (is != null) { is.close(); } } catch (Exception e) { Log.e("Error reading file", e.toString()); } ByteArrayOutputStream baos = new ByteArrayOutputStream(); bMap.compress(Bitmap.CompressFormat.JPEG, 100, baos); byte[] b = baos.toByteArray(); String data_string=Base64.encodeToString(b,Base64.DEFAULT); b=null;bMap=null; b=Base64.decode(data_string, Base64.DEFAULT); bMap=BitmapFactory.decodeByteArray(b, 0, b.length); image.setImageBitmap(bMap);
推荐答案
I wrote a small app that allowed for sending images taken with the phone's camera to a database. Here's how I solved the thing...
public void writeCommentForRestaurant(int id, String comment, String author, Bitmap image) { if (image != null) { /* Get the image as string */ // Normal ByteArrayOutputStream full_stream = new ByteArrayOutputStream(); image.compress(Bitmap.CompressFormat.PNG, 100, full_stream); byte[] full_bytes = full_stream.toByteArray(); String img_full = Base64.encodeToString(full_bytes, Base64.DEFAULT); // Thumbnail ByteArrayOutputStream thumb_stream = new ByteArrayOutputStream(); // The getScaledBitmap method only minimizes the Bitmap to a small icon! getScaledBitmap(image, 72).compress(Bitmap.CompressFormat.JPEG, 75, thumb_stream); byte[] thumb_bytes = thumb_stream.toByteArray(); String img_thumbnail = Base64.encodeToString(thumb_bytes, Base64.DEFAULT); // new HTTPWorker(ctx, mHandler, HTTPWorker.WRITE_COMMENT, true).execute( // Integer.toString(id), comment, author, img_thumbnail, img_full); } else { // new HTTPWorker(ctx, mHandler, HTTPWorker.WRITE_COMMENT, true).execute( // Integer.toString(id), comment, author, null, null); } }
The HTTPWorker is just an asynctask that constructs the HTTPmethod.
... /* Add arguments */ arguments.add(new BasicNameValuePair("idrestaurant", params[0])); arguments.add(new BasicNameValuePair("comment", params[1])); arguments.add(new BasicNameValuePair("author", params[2])); if (params.length > 3) { arguments.add(new BasicNameValuePair("image", params[3])); arguments.add(new BasicNameValuePair("bigimage", params[4])); } ...
And then I sent it to the server like this.
/** * Executes a httppost to a server instance with the given POST arguments * and returns a String response from the server. */ private String httppost(String url, ArrayList<NameValuePair> args) { /* Create the channel for communicaton */ InputStream is = null; /* Send request to server */ try { /* Create the POST */ HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(url); /* Add the login information "POST" variables in the php */ httppost.setEntity(new UrlEncodedFormEntity(args)); /* Execute the http POST and get the response */ HttpResponse response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); is = entity.getContent(); } catch (Exception e) { Log.e(TAG, "Error in http connection " + e.toString()); return null; } /* Read response from server */ try { /* Read the response stream */ BufferedReader reader = new BufferedReader(new InputStreamReader( is, "iso-8859-1"), 8); /* Copy the response to StringBuilder */ StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } is.close(); /* Return the response as string */ return sb.toString(); } catch (Exception e) { Log.e(TAG, "Error converting result " + e.toString()); return null; } }
其他推荐答案
Well thank you. Actually, the problem was from the server. The base64 is sent to a php script which stores the string into a field... which was a longtext type (mysql). The thing is that corrupts the data, I changed it to blob and it worked fine. Typical isn't it ?
Thanks a lot for your help.
My first topic and a great community is here that's great.
See you later.