我对这段代码有很大的问题。我的目标是通过php将图像(存储在我的SD卡中)发送到我的服务器。这是代码。我也使用过这4个库
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.Base64;
import com.loopj.android.http.RequestParams;
public void mytry(){
String fileName = Environment.getExternalStorageDirectory() + "/myImage.png";
String fileNameSegments[] = imgPath.split("/");
fileName = fileNameSegments[fileNameSegments.length - 1];
params.put("filename", fileName);
if (imgPath != null && !imgPath.isEmpty()) {
encodeImagetoString();
}
else {
Log.v("NO","no File");
}
}
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) {
Log.v("OK","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();
}
public void makeHTTPCall() {
AsyncHttpClient client = new AsyncHttpClient();
client.post("http://mywebsite.com/phppage.php", params, new AsyncHttpResponseHandler() {
@Override
public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) {
Log.v("Fail","Epic fail");
// TODO Auto-generated method stub
// When Http response code is '404'
if (statusCode == 404) {
Log.v("NO","Requested resource not found");
}
// When Http response code is '500'
else if (statusCode == 500) {
Log.v("NO","Something went wrong at server end");
}
// When Http response code other than 404, 500
else {
Log.v("NO","Error Occured \n Most Common Error: \n1. Device not connected to Internet\n2. Web App is not deployed in App server\n3. App server is not running\n HTTP Status code : "
+ String.valueOf(statusCode));
}
}
@Override
public void onSuccess(int statusCode, Header[] headers, byte[] response) {
// TODO Auto-generated method stub
// Hide Progress Dialog
Log.v("Yeah",String.valueOf(statusCode));
Log.v("Yeah",String.valueOf(headers));
Log.v("Yeah",String.valueOf(response));
}
});
}
这里是php代码:
<?php
$filename = $_REQUEST['filename'];
$base=$_REQUEST['image'];
$binary=base64_decode($base);
header('Content-Type: image/png; charset=utf-8');
$file = fopen("uploads/".$filename, 'wb');
fwrite($file, $binary);
fclose($file);
?>
当我运行我的应用程序时,我得到“成功”(响应200等等),但我的php页面看起来确实收到了任何内容。我已经花了两天时间。
提前谢谢