上传图片从机器人到PHP服务器 [英] Uploading Image from android to PHP server
本文介绍了上传图片从机器人到PHP服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在我的应用程序,我上传图片,从我的设备到本地Web服务器... 执行codeA .jpg文件后,被在服务器上创建,但它并没有被打开。 和在服务器中的文件的大小是从原始文件不同
Android的活动: -
公共类MainActivity延伸活动{
私有静态诠释RESULT_LOAD_IMAGE = 1;
@覆盖
保护无效的onCreate(包savedInstanceState){
super.onCreate(savedInstanceState);
的setContentView(R.layout.activity_main);
按钮btnSelectImage =(按钮)findViewById(R.id.uploadButton);
btnSelectImage.setOnClickListener(新OnClickListener(){
@覆盖
公共无效的onClick(视图v){
意图I =新的意图(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(ⅰ,RESULT_LOAD_IMAGE);
}
});
}
@覆盖
保护无效onActivityResult(INT申请code,INT结果code,意图数据){
// TODO自动生成方法存根
super.onActivityResult(要求code,因此code,数据);
如果(要求code == RESULT_LOAD_IMAGE和放大器;&安培;结果code == RESULT_OK和放大器;&安培;!数据= NULL){
乌里selectedImage = data.getData();
的String [] filePathColumn = {MediaStore.Images.Media.DATA};
光标光标= getContentResolver()查询(selectedImage,filePathColumn,NULL,NULL,NULL);
cursor.moveToFirst();
INT参数:columnIndex = cursor.getColumnIndex(filePathColumn [0]);
字符串picturePath = cursor.getString(参数:columnIndex);
cursor.close();
点阵位图= BitmapFactory.de codeFILE(picturePath);
ImageView的IM =(ImageView的)findViewById(R.id.imgBox);
im.setImageBitmap(位);
/ *
*将图像转换为字符串
* * /
ByteArrayOutputStream流=新ByteArrayOutputStream();
bitmap.com preSS(Bitmap.Com pressFormat.PNG,90,流); // COM preSS到你想要的格式。
byte []的byte_arr = stream.toByteArray();
字符串image_str = Base64.en codeToString(byte_arr,Base64.DEFAULT);
/ *
*创建一个名称值对的图像串要传递给服务器
* * /
ArrayList的<的NameValuePair> namevaluepairs中=新的ArrayList<的NameValuePair>();
nameValuePairs.add(新BasicNameValuePair(形象,image_str));
JSONObject的jsonString =新的JSONObject();
尝试 {
jsonString.put(IMG,image_str);
}赶上(JSONException E){
// TODO自动生成的catch块
e.printStackTrace();
}
新uploadImageToPhp()执行(jsonString);
}
}
@覆盖
公共布尔onCreateOptionsMenu(功能菜单){
//充气菜单;这增加了项目操作栏,如果它是present。
。getMenuInflater()膨胀(R.menu.main,菜单);
返回true;
}
公共类uploadImageToPhp扩展的AsyncTask< JSONObject的,太虚,太虚>
{
字符串dataToSend = NULL;
公共静态最后弦乐preFIX =HTTP://; // $ P $的网址PFIX
公共静态最后弦乐SERVER_IP =172.16.26.155; // IP地址所在的PHP服务器位于
公共静态最后弦乐completeServerAddress = preFIX + SERVER_IP +/ test_upload / upload_image.php; //在PHP文件的精确位置
@覆盖
保护无效doInBackground(JSONObject的... PARAMS){
dataToSend =形象=+参数[0];
通讯(completeServerAddress,dataToSend);
返回null;
}
公共无效的沟通(字符串urlString,字符串dataToSend2)
{
字符串结果= NULL;
尝试
{
网址URL =新的URL(urlString);
URLConnection的康恩= url.openConnection();
HttpURLConnection的httpConn =(HttpURLConnection类),康涅狄格州;
httpConn.setRequestProperty(接受,应用/ JSON);
httpConn.setRequestProperty(接收字符集,UTF-8);
httpConn.setRequestMethod(POST);
httpConn.connect();
//创建一个输出流数据发送给服务器
OutputStreamWriter OUT =新OutputStreamWriter(httpConn.getOutputStream());
out.write(dataToSend2);
了out.flush();
INT则httpStatus = httpConn.getResponse code();
的System.out.println(HTTP状态:+则httpStatus);
如果(则httpStatus == HttpURLConnection.HTTP_OK)
{
Log.d(HTTP状态,HTTP连接成功);
的BufferedReader在=新的BufferedReader(新的InputStreamReader(httpConn.getInputStream(),UTF-8));
StringBuilder的SB =新的StringBuilder();
字符串inputLine;
而((inputLine = in.readLine())!= NULL)
{
的System.out.println(inputLine);
sb.append(inputLine +\ N);
}
附寄();
结果= sb.toString();
尝试
{
// jsonResult =新的JSONObject的(结果);
}
赶上(例外五)
{
Log.e(JSON解析器,错误分析数据+ e.toString());
}
}
其他
{
的System.out.println(财产以后出了问题);
}
}赶上(MalformedURLException异常E){
// TODO自动生成的catch块
e.printStackTrace();
}赶上(IOException异常E){
// TODO自动生成的catch块
e.printStackTrace();
}
}
}
}
PHP code: -
$ recievedJson = $ _ REQUEST ['形象'];
$ imageContent = json_de code($ recievedJson,真正的);
$基地= $ imageContent [IMG];
$二进制= base64_de code($基地);
回声$二进制;
标题(内容类型:位图;字符集= UTF-8);
$文件=的fopen('uploaded_image.jpg,世行);
FWRITE($文件,$二);
fclose函数($文件);
解决方案
使用低于code。它会做同样的。
公共类UploadImage延伸活动{
InputStream中的InputStream;
@覆盖
公共无效的onCreate(包冰柱){
super.onCreate(冰柱);
的setContentView(R.layout.main);
点阵位图= BitmapFactory.de codeResource(getResources(),R.drawable.icon); ByteArrayOutputStream流=新ByteArrayOutputStream();
bitmap.com preSS(Bitmap.Com pressFormat.PNG,90,流); // COM preSS到你想要的格式。
byte []的byte_arr = stream.toByteArray();
字符串image_str = Base64.en codeBytes(byte_arr);
ArrayList的<的NameValuePair> namevaluepairs中=新的ArrayList<的NameValuePair>();
nameValuePairs.add(新BasicNameValuePair(形象,image_str));
线程t =新主题(新的Runnable(){
@覆盖
公共无效的run(){
尝试{
HttpClient的HttpClient的=新DefaultHttpClient();
HttpPost httppost =新HttpPost(服务器的链接/文件夹名称/ upload_image.php);
httppost.setEntity(新UrlEn codedFormEntity(namevaluepairs中));
HTT presponse响应= httpclient.execute(httppost);
串the_string_response = convertResponseToString(响应);
runOnUiThread(新的Runnable(){
@覆盖
公共无效的run(){
Toast.makeText(UploadImage.this,响应+ the_string_response,Toast.LENGTH_LONG).show();
}
});
}赶上(例外五){
runOnUiThread(新的Runnable(){
@覆盖
公共无效的run(){
Toast.makeText(UploadImage.this,ERROR+ e.getMessage(),Toast.LENGTH_LONG).show();
}
});
的System.out.println(在HTTP连接错误+ e.toString());
}
}
});
t.start();
}
公共字符串convertResponseToString(Htt的presponse响应)抛出IllegalStateException异常,IOException异常{
字符串资源=;
StringBuffer的缓冲区=新的StringBuffer();
的InputStream = response.getEntity()的getContent()。
INT CONTENTLENGTH =(int)的response.getEntity()getContentLength()。 //获取内容长度... ..
runOnUiThread(新的Runnable(){
@覆盖
公共无效的run(){
Toast.makeText(UploadImage.thisCONTENTLENGTH:+ CONTENTLENGTH,Toast.LENGTH_LONG).show();
}
});
如果(CONTENTLENGTH℃,){
}
其他{
byte []的数据=新的字节[512];
INT的len = 0;
尝试
{
而(-1!=(LEN = inputStream.read(数据)))
{
buffer.append(新的字符串(data,0,len个)); //转换为字符串,并追加到StringBuffer的... ..
}
}
赶上(IOException异常E)
{
e.printStackTrace();
}
尝试
{
inputStream.close(); //关闭流......
}
赶上(IOException异常E)
{
e.printStackTrace();
}
RES = buffer.toString(); //转换StringBuffer来串... ..
runOnUiThread(新的Runnable(){
@覆盖
公共无效的run(){
Toast.makeText(UploadImage.this,结果:+资源,Toast.LENGTH_LONG).show();
}
});
//System.out.println("Response =>中+ EntityUtils.toString(response.getEntity()));
}
返回水库;
}
}
PHP code
< PHP
$基地= $ _ REQUEST ['形象'];
$二进制= base64_de code($基地);
标题(内容类型:位图;字符集= UTF-8);
$文件=的fopen('uploaded_image.jpg,世行);
FWRITE($文件,$二);
fclose函数($文件);
回声图片上传完成!,请检查你的PHP文件目录......;
?>
In my app i am uploading an image from my device to a local web server... after executing the code a .jpg file gets created in the server but it does not gets opened. And the size of the file in server is different from the original file.
Android activity:--
public class MainActivity extends Activity {
private static int RESULT_LOAD_IMAGE = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnSelectImage=(Button) findViewById(R.id.uploadButton);
btnSelectImage.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent i=new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && data!=null) {
Uri selectedImage=data.getData();
String[] filePathColumn={MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage,filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
Bitmap bitmap=BitmapFactory.decodeFile(picturePath);
ImageView im = (ImageView) findViewById(R.id.imgBox);
im.setImageBitmap(bitmap);
/*
* Convert the image to a string
* */
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 90, stream); //compress to which format you want.
byte [] byte_arr = stream.toByteArray();
String image_str = Base64.encodeToString(byte_arr,Base64.DEFAULT);
/*
* Create a name value pair for the image string to be passed to the server
* */
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("image",image_str));
JSONObject jsonString=new JSONObject();
try {
jsonString.put("img", image_str);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
new uploadImageToPhp().execute(jsonString);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public class uploadImageToPhp extends AsyncTask<JSONObject, Void, Void>
{
String dataToSend=null;
public static final String prefix="http://"; //prefix of the urls
public static final String server_ip="172.16.26.155"; //the ip address where the php server is located
public static final String completeServerAddress=prefix+server_ip+"/test_upload/upload_image.php"; //Exact location of the php files
@Override
protected Void doInBackground(JSONObject... params) {
dataToSend="image="+params[0];
communicator(completeServerAddress, dataToSend);
return null;
}
public void communicator(String urlString,String dataToSend2)
{
String result=null;
try
{
URL url=new URL(urlString);
URLConnection conn=url.openConnection();
HttpURLConnection httpConn=(HttpURLConnection) conn;
httpConn.setRequestProperty("Accept", "application/json");
httpConn.setRequestProperty("accept-charset", "UTF-8");
httpConn.setRequestMethod("POST");
httpConn.connect();
//Create an output stream to send data to the server
OutputStreamWriter out=new OutputStreamWriter(httpConn.getOutputStream());
out.write(dataToSend2);
out.flush();
int httpStatus = httpConn.getResponseCode();
System.out.println("Http status :"+httpStatus);
if(httpStatus==HttpURLConnection.HTTP_OK)
{
Log.d("HTTP STatus", "http connection successful");
BufferedReader in = new BufferedReader(new InputStreamReader(httpConn.getInputStream(),"UTF-8"));
StringBuilder sb = new StringBuilder();
String inputLine;
while ((inputLine = in.readLine()) != null)
{
System.out.println(inputLine);
sb.append(inputLine+"\n");
}
in.close();
result=sb.toString();
try
{
//jsonResult = new JSONObject(result);
}
catch(Exception e)
{
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
}
else
{
System.out.println("Somthing went wrong");
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
PHP code:-
$recievedJson=$_REQUEST['image'];
$imageContent=json_decode($recievedJson,true);
$base=$imageContent["img"];
$binary=base64_decode($base);
echo $binary;
header('Content-Type: bitmap; charset=utf-8');
$file = fopen('uploaded_image.jpg', 'wb');
fwrite($file, $binary);
fclose($file);
解决方案
Use below code. It will do the same.
public class UploadImage extends Activity {
InputStream inputStream;
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
Bitmap bitmap = BitmapFactory.decodeResource(getResources(),R.drawable.icon); ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 90, stream); //compress to which format you want.
byte [] byte_arr = stream.toByteArray();
String image_str = Base64.encodeBytes(byte_arr);
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("image",image_str));
Thread t = new Thread(new Runnable() {
@Override
public void run() {
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("server-link/folder-name/upload_image.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
String the_string_response = convertResponseToString(response);
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(UploadImage.this, "Response " + the_string_response, Toast.LENGTH_LONG).show();
}
});
}catch(Exception e){
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(UploadImage.this, "ERROR " + e.getMessage(), Toast.LENGTH_LONG).show();
}
});
System.out.println("Error in http connection "+e.toString());
}
}
});
t.start();
}
public String convertResponseToString(HttpResponse response) throws IllegalStateException, IOException{
String res = "";
StringBuffer buffer = new StringBuffer();
inputStream = response.getEntity().getContent();
int contentLength = (int) response.getEntity().getContentLength(); //getting content length…..
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(UploadImage.this, "contentLength : " + contentLength, Toast.LENGTH_LONG).show();
}
});
if (contentLength < 0){
}
else{
byte[] data = new byte[512];
int len = 0;
try
{
while (-1 != (len = inputStream.read(data)) )
{
buffer.append(new String(data, 0, len)); //converting to string and appending to stringbuffer…..
}
}
catch (IOException e)
{
e.printStackTrace();
}
try
{
inputStream.close(); // closing the stream…..
}
catch (IOException e)
{
e.printStackTrace();
}
res = buffer.toString(); // converting stringbuffer to string…..
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(UploadImage.this, "Result : " + res, Toast.LENGTH_LONG).show();
}
});
//System.out.println("Response => " + EntityUtils.toString(response.getEntity()));
}
return res;
}
}
PHP Code
<?php
$base=$_REQUEST['image'];
$binary=base64_decode($base);
header('Content-Type: bitmap; charset=utf-8');
$file = fopen('uploaded_image.jpg', 'wb');
fwrite($file, $binary);
fclose($file);
echo 'Image upload complete!!, Please check your php file directory……';
?>
这篇关于上传图片从机器人到PHP服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文