将图像从android上传到PHP服务器
在我的应用程序中,我正在将图像从我的设备上载到本地web服务器。。。 执行代码后,会在服务器中创建一个.jpg文件,但不会打开它。 并且服务器中的文件大小与原始文件不同 Android活动:---将图像从android上传到PHP服务器,php,android,image-uploading,Php,Android,Image Uploading,在我的应用程序中,我正在将图像从我的设备上载到本地web服务器。。。 执行代码后,会在服务器中创建一个.jpg文件,但不会打开它。 并且服务器中的文件大小与原始文件不同 Android活动:--- public class MainActivity extends Activity { private static int RESULT_LOAD_IMAGE = 1; @Override protected void onCreate(Bundle savedInstanceState) {
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();
}
}
}
}
$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);
使用下面的代码。它也会这样做
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;
}
}
公共类上载映像扩展活动{
输入流输入流;
@凌驾
创建公共空间(捆绑冰柱){
超级冰柱;
setContentView(R.layout.main);
位图Bitmap=BitmapFactory.decodeResource(getResources(),R.drawable.icon);ByteArrayOutputStream=new ByteArrayOutputStream();
compress(bitmap.CompressFormat.PNG,90,stream);//压缩为所需格式。
byte[]byte_arr=stream.toByteArray();
字符串image\u str=Base64.encodeBytes(byte\u arr);
ArrayList nameValuePairs=新的ArrayList();
添加(新的BasicNameValuePair(“image”,image_str));
线程t=新线程(新的可运行线程(){
@凌驾
公开募捐{
试一试{
HttpClient HttpClient=新的DefaultHttpClient();
HttpPost-HttpPost=newhttppost(“服务器链接/文件夹名称/upload_image.php”);
setEntity(新的UrlEncodedFormEntity(nameValuePairs));
HttpResponse response=httpclient.execute(httppost);
字符串\u字符串\u响应=convertResponseToString(响应);
runOnUiThread(新的Runnable(){
@凌驾
公开募捐{
Toast.makeText(UploadImage.this,“Response”+字符串响应Toast.LENGTH.LONG.show();
}
});
}捕获(例外e){
runOnUiThread(新的Runnable(){
@凌驾
公开募捐{
Toast.makeText(UploadImage.this,“ERROR”+e.getMessage(),Toast.LENGTH\u LONG.show();
}
});
System.out.println(“http连接中的错误”+e.toString());
}
}
});
t、 start();
}
公共字符串convertResponseToString(HttpResponse响应)引发IllegalStateException,IOException{
字符串res=“”;
StringBuffer=新的StringBuffer();
inputStream=response.getEntity().getContent();
int contentLength=(int)response.getEntity().getContentLength();//获取内容长度…。。
runOnUiThread(新的Runnable(){
@凌驾
公开募捐{
Toast.makeText(UploadImage.this,“contentLength:+contentLength,Toast.LENGTH_LONG).show();
}
});
if(contentLength<0){
}
否则{
字节[]数据=新字节[512];
int len=0;
尝试
{
而(-1!=(len=inputStream.read(data)))
{
append(新字符串(数据,0,len));//转换为字符串并追加到stringbuffer…。。
}
}
捕获(IOE异常)
{
e、 printStackTrace();
}
尝试
{
inputStream.close();//关闭流…。。
}
捕获(IOE异常)
{
e、 printStackTrace();
}
res=buffer.toString();//正在将stringbuffer转换为字符串…。。
runOnUiThread(新的Runnable(){
@凌驾
公开募捐{
Toast.makeText(UploadImage.this,“结果:+res,Toast.LENGTH_LONG).show();
}
});
//System.out.println(“Response=>”+EntityUtils.toString(Response.getEntity());
}
返回res;
}
}
PHP代码
<?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……';
?>
更新
NameValuePair和Http类已被弃用,因此,我尝试了这段代码,它对我有效。希望有帮助
private void uploadImage(Bitmap imageBitmap){
ByteArrayOutputStream stream = new ByteArrayOutputStream();
imageBitmap.compress(Bitmap.CompressFormat.PNG, 90, stream);
byte[] b = stream.toByteArray();
String encodedImage = Base64.encodeToString(b, Base64.DEFAULT);
ArrayList<Pair<String, String>> params = new ArrayList<Pair<String, String>>();
params.add(new Pair<>("image", encodedImage));
try {
new AsyncUploader().execute(my_upload_php, getQuery(params));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
private String getQuery(List<Pair<String, String>> params) throws UnsupportedEncodingException{
StringBuilder result = new StringBuilder();
boolean first = true;
for(Pair<String, String> pair : params){
if(first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(pair.first, "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(pair.second, "UTF-8"));
}
return result.toString();
}
private class AsyncUploader extends AsyncTask<String, Integer, String>
{
@Override
protected String doInBackground(String... strings) {
String urlString = strings[0];
String params = strings[1];
URL url = null;
InputStream stream = null;
HttpURLConnection urlConnection = null;
try {
url = new URL(urlString);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.setDoOutput(true);
urlConnection.connect();
OutputStreamWriter wr = new OutputStreamWriter(urlConnection.getOutputStream());
wr.write(params);
wr.flush();
stream = urlConnection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(stream, "UTF-8"), 8);
String result = reader.readLine();
return result;
}catch (IOException ioe){
ioe.printStackTrace();
} finally {
if (urlConnection != null)
urlConnection.disconnect();
}
return null;
}
@Override
protected void onPostExecute(String result) {
Toast.makeText(MakePhoto.this, result, Toast.LENGTH_SHORT).show();
}
}
private void上传图像(位图图像位图){
ByteArrayOutputStream=新建ByteArrayOutputStream();
imageBitmap.compress(Bitmap.CompressFormat.PNG,90,流);
字节[]b=stream.toByteArray();
字符串encodedImage=Base64.encodeToString(b,Base64.DEFAULT);
ArrayList params=新的ArrayList();
参数添加(新对(“图像”,encodedImage));
试一试{
新建AsyncUploader().execute(my_upload_php,getQuery(params));
}捕获(不支持的编码异常e){
e、 printStackTrace();
}
}
私有字符串getQuery(列表参数)引发UnsupportedEncodingException{
StringBuilder结果=新建StringBuilder();
布尔值优先=真;
for(配对:params){
如果(第一)
第一个=假;
其他的
结果。追加(&);
result.append(URLEncoder.encode(pair.first,“UTF-8”);
结果。追加(“=”);
result.append(URLEncoder.encode(pair.second,“UTF-8”);
}
返回result.toString();
}
私有类AsyncUploader扩展AsyncTask
{
@凌驾
受保护的字符串背景(字符串…字符串){
字符串urlString=strings[0];
字符串参数
public JSONObject getJSONFromUrlPost(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("id",
new StringBody(userid, Charset.forName("UTF-8")));
entity.addPart("sharestatus",
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);
return new JSONObject(response.toString());
} catch (Exception e) {
return null;
}
}
------------------------------------------------------------------
in main.java
JSONParser js = new JSONParser();
String url="";// upload file with Server url
JSONObject data = js.getJSONFromUrlPost(url);
String response;
try {
response = data.getString("Msg");
if (response.contains("Succesfully upload file")) {
JSONObject jsondata = new JSONObject(data.getString("Data"));
Fileurl = jsondata.getString("Url");
}
} catch (Exception e) {
e.printStackTrace();
}