Android上传图像php服务器使用AsynTask
嗨,伙计们。 我试着把一个文件作为服务器上传到我的笔记本电脑上。为什么我的每一个错误都是这样=Android上传图像php服务器使用AsynTask,php,android,asynchronous,server,Php,Android,Asynchronous,Server,嗨,伙计们。 我试着把一个文件作为服务器上传到我的笔记本电脑上。为什么我的每一个错误都是这样= <br/> <Parse error> </ br> syntax error, unexpected T_Variable in <b> /imgupload/upload_image.php </ b> on line <b> 6 </ b> <br/> 语法错误,第6行/imgupload/upl
<br/> <Parse error> </ br> syntax error, unexpected T_Variable in <b> /imgupload/upload_image.php </ b> on line <b> 6 </ b> <br/>
语法错误,第6行/imgupload/upload_image.php中出现意外的T_变量
这是我的android代码
import java.io.ByteArrayOutputStream;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Base64;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
@SuppressLint("NewApi")
public class MainActivity extends Activity {
ProgressDialog prgDialog;
String encodedString;
RequestParams params = new RequestParams();
String imgPath, fileName;
Bitmap bitmap;
private static int RESULT_LOAD_IMG = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
prgDialog = new ProgressDialog(this);
// Set Cancelable as False
prgDialog.setCancelable(false);
}
public void loadImagefromGallery(View view) {
// Create intent to Open Image applications like Gallery, Google Photos
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
// Start the Intent
startActivityForResult(galleryIntent, RESULT_LOAD_IMG);
}
// When Image is selected from Gallery
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
// When an Image is picked
if (requestCode == RESULT_LOAD_IMG && resultCode == RESULT_OK
&& null != data) {
// Get the Image from data
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
// Get the cursor
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
// Move to first row
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
imgPath = cursor.getString(columnIndex);
cursor.close();
ImageView imgView = (ImageView) findViewById(R.id.imgView);
// Set the Image in ImageView
imgView.setImageBitmap(BitmapFactory
.decodeFile(imgPath));
// Get the Image's file name
String fileNameSegments[] = imgPath.split("/");
fileName = fileNameSegments[fileNameSegments.length - 1];
// Put file name in Async Http Post Param which will used in Php web app
params.put("filename", fileName);
} else {
Toast.makeText(this, "You haven't picked Image",
Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG)
.show();
}
}
// When Upload button is clicked
public void uploadImage(View v) {
// When Image is selected from Gallery
if (imgPath != null && !imgPath.isEmpty()) {
prgDialog.setMessage("Converting Image to Binary Data");
prgDialog.show();
// Convert image to String using Base64
encodeImagetoString();
// When Image is not selected from Gallery
} else {
Toast.makeText(
getApplicationContext(),
"You must select image from gallery before you try to upload",
Toast.LENGTH_LONG).show();
}
}
// AsyncTask - To convert Image to String
public void encodeImagetoString() {
new AsyncTask<Void, Void, String>() {
protected void onPreExecute() {
};
@Override
protected String doInBackground(Void... params) {
BitmapFactory.Options options = null;
options = new BitmapFactory.Options();
options.inSampleSize = 3;
bitmap = BitmapFactory.decodeFile(imgPath,
options);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
// Must compress the Image to reduce image size to make upload easy
bitmap.compress(Bitmap.CompressFormat.PNG, 50, stream);
byte[] byte_arr = stream.toByteArray();
// Encode Image to String
encodedString = Base64.encodeToString(byte_arr, 0);
return "";
}
@Override
protected void onPostExecute(String msg) {
prgDialog.setMessage("Calling Upload");
// Put converted Image string into Async Http Post param
params.put("image", encodedString);
// Trigger Image upload
triggerImageUpload();
}
}.execute(null, null, null);
}
public void triggerImageUpload() {
makeHTTPCall();
}
// Make Http call to upload Image to Php server
public void makeHTTPCall() {
prgDialog.setMessage("Invoking Php");
AsyncHttpClient client = new AsyncHttpClient();
// Don't forget to change the IP address to your LAN address. Port no as well.
client.post("http://192.168.2.43/imgupload/upload_image.php",
params, new AsyncHttpResponseHandler() {
// When the response returned by REST has Http
// response code '200'
@Override
public void onSuccess(String response) {
// Hide Progress Dialog
prgDialog.hide();
Toast.makeText(getApplicationContext(), response,
Toast.LENGTH_LONG).show();
}
// When the response returned by REST has Http
// response code other than '200' such as '404',
// '500' or '403' etc
@Override
public void onFailure(int statusCode, Throwable error,
String content) {
// Hide Progress Dialog
prgDialog.hide();
// When Http response code is '404'
if (statusCode == 404) {
Toast.makeText(getApplicationContext(),
"Requested resource not found",
Toast.LENGTH_LONG).show();
}
// When Http response code is '500'
else if (statusCode == 500) {
Toast.makeText(getApplicationContext(),
"Something went wrong at server end",
Toast.LENGTH_LONG).show();
}
// When Http response code other than 404, 500
else {
Toast.makeText(
getApplicationContext(),
"Error Occured n Most Common Error: n1. Device not connected to Internetn2. Web App is not deployed in App servern3. App server is not runningn HTTP Status code : "
+ statusCode, Toast.LENGTH_LONG)
.show();
}
}
});
}
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
// Dismiss the progress bar when application is closed
if (prgDialog != null) {
prgDialog.dismiss();
}
}
}
import java.io.ByteArrayOutputStream;
导入android.annotation.SuppressLint;
导入android.app.Activity;
导入android.app.ProgressDialog;
导入android.content.Intent;
导入android.database.Cursor;
导入android.graphics.Bitmap;
导入android.graphics.BitmapFactory;
导入android.net.Uri;
导入android.os.AsyncTask;
导入android.os.Bundle;
导入android.provider.MediaStore;
导入android.util.Base64;
导入android.view.view;
导入android.widget.ImageView;
导入android.widget.Toast;
导入com.loopj.android.http.AsyncHttpClient;
导入com.loopj.android.http.AsyncHttpResponseHandler;
导入com.loopj.android.http.RequestParams;
@SuppressLint(“新API”)
公共类MainActivity扩展了活动{
进程对话;
字符串编码字符串;
RequestParams params=新的RequestParams();
字符串imgPath,文件名;
位图;
私有静态int结果\加载\ IMG=1;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
prgDialog=新建进度对话框(此对话框);
//将可取消设置为False
prgDialog.setCancelable(假);
}
公共void loadImagefromGallery(视图){
//创建用于打开Gallery、Google Photos等图像应用程序的意图
Intent gallerycontent=新意图(Intent.ACTION\u PICK,
android.provider.MediaStore.Images.Media.EXTERNAL\u CONTENT\u URI);
//开始意图
startActivityForResult(GalleryContent、RESULT\u LOAD\u IMG);
}
//从库中选择图像时
@凌驾
受保护的void onActivityResult(int请求代码、int结果代码、意图数据){
super.onActivityResult(请求代码、结果代码、数据);
试一试{
//拾取图像时
如果(requestCode==RESULT\u LOAD\u IMG&&resultCode==RESULT\u OK
&&空!=数据){
//从数据中获取图像
Uri selectedImage=data.getData();
字符串[]filePathColumn={MediaStore.Images.Media.DATA};
//获取光标
Cursor Cursor=getContentResolver().query(selectedImage,
filePathColumn,null,null,null);
//移到第一排
cursor.moveToFirst();
int columnIndex=cursor.getColumnIndex(filePathColumn[0]);
imgPath=cursor.getString(columnIndex);
cursor.close();
ImageView imgView=(ImageView)findViewById(R.id.imgView);
//在ImageView中设置图像
imgView.setImageBitmap(位图工厂
.decodeFile(imgPath));
//获取图像的文件名
字符串fileNameSegments[]=imgPath.split(“/”);
fileName=fileNameSegments[fileNameSegments.length-1];
//将文件名放入将在Php web应用程序中使用的异步Http Post参数中
参数put(“文件名”,文件名);
}否则{
Toast.makeText(这是“您还没有选择图像”,
Toast.LENGTH_LONG).show();
}
}捕获(例外e){
Toast.makeText(这个“出错了”,Toast.LENGTH\u LONG)
.show();
}
}
//单击上载按钮时
公共无效上载映像(视图v){
//从库中选择图像时
if(imgPath!=null&&!imgPath.isEmpty()){
setMessage(“将图像转换为二进制数据”);
prgDialog.show();
//使用Base64将图像转换为字符串
encodeImagetoString();
//未从库中选择图像时
}否则{
Toast.makeText(
getApplicationContext(),
“您必须先从图库中选择图像,然后才能尝试上载”,
Toast.LENGTH_LONG).show();
}
}
//AsyncTask-将图像转换为字符串
public void encodeImagetoString(){
新建异步任务(){
受保护的void onPreExecute(){
};
@凌驾
受保护字符串doInBackground(无效…参数){
BitmapFactory.Options=null;
options=新的BitmapFactory.options();
options.inSampleSize=3;
位图=位图工厂.decodeFile(imgPath,
选择权);
ByteArrayOutputStream=新建ByteArrayOutputStream();
//必须压缩图像以减小图像大小,以便于上传
compress(bitmap.CompressFormat.PNG,50,流);
byte[]byte_arr=stream.toByteArray();
//将图像编码为字符串
encodedString=Base64.encodeToString(字节_arr,0);
返回“”;
}
@凌驾
受保护的void onPostExecute(字符串msg){
设置消息(“调用上载”);
//将转换后的图像字符串放入异步Http Post参数
参数put(“图像”,编码字符串);
//触发图像上传
triggerImageUpload();
}
}.执行(空,空,空);
}
public void triggerImageUpload(){
makeHTTPCall();
}
//进行Http调用以将图像上载到Php服务器
public void makeHTTPCall(){
setMessage(“调用Php”);
AsyncHttpClient=新的AsyncHttpClient();
//不要忘记将IP地址更改为LAN地址。端口号a
<?php
// Get image string posted from Android App
$base=$_REQUEST['image'];
// Get file name posted from Android App
$filename = $_REQUEST['filename'];
// Decode Image
$binary=base64_decode($base);
header('Content-Type: bitmap; charset=utf-8');
// Images will be saved under 'www/imgupload/uplodedimages' folder
$file = fopen('uploadedimages/'.$filename, 'wb');
// Create File
fwrite($file, $binary);
fclose($file);
echo 'Image upload complete, Please check your php file directory';
?>
public String multipartRequest(final String urlTo, final String post, final String filepath, final String filefield) throws ParseException, IOException {
String result = "";
HttpURLConnection connection = null;
DataOutputStream outputStream = null;
InputStream inputStream = null;
String twoHyphens = "--";
String boundary = "---------------------------14737809831466499882746641449";
String lineEnd = "\r\n";
result = "";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1*1024*1024;
String[] q = filepath.split("/");
int idx = q.length - 1;
try {
File file = new File(getActivity().getFilesDir(), filepath);
FileInputStream fileInputStream = new FileInputStream(file);
URL url = new URL(urlTo);
connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("User-Agent", "Android Multipart HTTP Client 1.0");
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary="+boundary);
outputStream = new DataOutputStream(connection.getOutputStream());
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
outputStream.writeBytes("Content-Disposition: form-data; name=\"" + filefield + "\"; filename=\"" + q[idx] +"\"" + lineEnd);
outputStream.writeBytes("Content-Type: image/png" + lineEnd);
outputStream.writeBytes("Content-Transfer-Encoding: binary" + lineEnd);
outputStream.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while(bytesRead > 0) {
outputStream.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
outputStream.writeBytes(lineEnd);
// Upload POST Data
String[] posts = post.split("&");
int max = posts.length;
for(int i=0; i<max;i++) {
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
int positionOfEqual = posts[i].indexOf("=");
if (posts[i].length() == (positionOfEqual + 1)) posts[i] = posts[i] + "_";
String kv[] = posts[i].split("=");
outputStream.writeBytes("Content-Disposition: form-data; name=\"" + kv[0] + "\"" + lineEnd);
outputStream.writeBytes("Content-Type: text/plain"+lineEnd);
outputStream.writeBytes(lineEnd);
outputStream.writeBytes(kv[1]);
outputStream.writeBytes(lineEnd);
}
outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
inputStream = connection.getInputStream();
result = convertStreamToString(inputStream);
fileInputStream.close();
inputStream.close();
outputStream.flush();
outputStream.close();
} catch(Exception e) {
Log.e("MultipartRequest", "Multipart Form Upload Error");
e.printStackTrace();
}
return result;
}
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}