我正在尝试向PHP服务器发送值,但总是,我得到HTTP REsponse 200并且在我的服务器中我没有得到我发送的值,不知道接下来的问题是我的Android和PHP的代码片段,可以任何人都帮我这个?...对不起代码......我也跟着这个Android file upload - $_FILES returns empty
PHP方面我使用了smarty framework
$print = false;
$header = true;
if(isset($_REQUEST['action']) && $_REQUEST['action'] =='imagetest')
{
$error = '0';
$val = basename($_FILES['image']['name']);
if($val != '')
{
$error = '1';
$msg = 'Image Not Upload Please Try Agin';
$param = array("status"=>"error","msg"=>$val);
$val = json_encode($param);
echo $val;
exit;
}
/*if($_FILES['image'] == '')
{
$error = '1';
$msg = 'Image Not Upload Please Try Agin';
$param = array("status"=>"error","msg"=>$msg);
$val = json_encode($param);
echo $val;
exit;
}*/
if($error == '0')
{
$target_path = "uploads/";
$target_path = $target_path . basename( $_FILES['image']['name']);
if(move_uploaded_file($_FILES['image']['tmp_name'], $target_path)) {
$msg = 'Image inserted successfully';
$param = array("status"=>"success","msg"=>$msg);
$val = json_encode($param);
echo $val;
exit;
} else{
$msg = 'Image not inserted successfully';
$param = array("status"=>"success","msg"=>$msg);
$val = json_encode($param);
echo $val;
exit;
}
}
}
else
{
$msg = 'something went wrong';
$param = array("status"=>"success","msg"=>$msg);
$val = json_encode($param);
echo $val;
exit;
}
MyjavaFile
uploadButton = (ImageView)findViewById(R.id.uploadButton);
uploadButton.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
dialog = ProgressDialog.show(PhotoUpload.this, "", "Uploading file...", true);
new Thread(new Runnable()
{
public void run()
{
runOnUiThread(new Runnable()
{
public void run()
{
messageText.setText("uploading started.....");
}
});
uploadFile(selectedImagePath);
}
}).start();
}
});
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1111) {
if (data!=null ) {
openGalleryImage(data);
//saveImage(uri_outputFileUri.getPath());
Uri selectedImageUri = data.getData();
Bitmap bitmap;
try {
bitmap = scaleImage(PhotoUpload.this,selectedImageUri);
img.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static Bitmap scaleImage(Context context, Uri photoUri) throws IOException {
InputStream is = context.getContentResolver().openInputStream(photoUri);
BitmapFactory.Options dbo = new BitmapFactory.Options();
dbo.inJustDecodeBounds = true;
BitmapFactory.decodeStream(is, null, dbo);
is.close();
int rotatedWidth, rotatedHeight;
int orientation = getOrientation(context, photoUri);
if (orientation == 90 || orientation == 270) {
rotatedWidth = dbo.outHeight;
rotatedHeight = dbo.outWidth;
} else {
rotatedWidth = dbo.outWidth;
rotatedHeight = dbo.outHeight;
}
Bitmap srcBitmap;
is = context.getContentResolver().openInputStream(photoUri);
if (rotatedWidth > 100 || rotatedHeight > 100) {
float widthRatio = ((float) rotatedWidth) / ((float) 100);
float heightRatio = ((float) rotatedHeight) / ((float) 100);
float maxRatio = Math.max(widthRatio, heightRatio);
// Create the bitmap from file
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = (int) maxRatio;
srcBitmap = BitmapFactory.decodeStream(is, null, options);
} else {
srcBitmap = BitmapFactory.decodeStream(is);
}
is.close();
if (orientation > 0) {
Matrix matrix = new Matrix();
matrix.postRotate(orientation);
srcBitmap = Bitmap.createBitmap(srcBitmap, 0, 0, srcBitmap.getWidth(),
srcBitmap.getHeight(), matrix, true);
}
String type = context.getContentResolver().getType(photoUri);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
if (type.equals("image/png")) {
srcBitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
} else if (type.equals("image/jpg") || type.equals("image/jpeg")) {
srcBitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
}
byte[] bMapArray = baos.toByteArray();
baos.close();
return BitmapFactory.decodeByteArray(bMapArray, 0, bMapArray.length);
}
public static int getOrientation(Context context, Uri photoUri) {
/* it's on the external media. */
Cursor cursor = context.getContentResolver().query(photoUri,
new String[] { MediaStore.Images.ImageColumns.ORIENTATION }, null, null, null);
if (cursor.getCount() != 1) {
return -1;
}
cursor.moveToFirst();
return cursor.getInt(0);
}
private void openGalleryImage(Intent data)
{
Uri selectedimg = data.getData();
Uri uriselectedimage=data.getData();
mString=uriselectedimage.getPath();
try
{
mInputStream= getContentResolver().openInputStream(selectedimg);
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
String[] path = { MediaStore.Images.Media.DATA };
Cursor c = getContentResolver().query(selectedimg, path, null, null,null);
c.moveToFirst();
int columnIndex = c.getColumnIndex(path[0]);
selectedImagePath=c.getString(columnIndex);
uri_outputFileUri= Uri.parse(selectedImagePath);
c.close();
}
private void saveImage(String mPath)
{
System.out.println("Paths "+mPath);
mediaDir= new File(Environment.getExternalStorageDirectory() +"/MyFolder");
mediaDir.mkdir();
File myImage = new File(mediaDir, Long.toString(System.currentTimeMillis()) + ".png");
try
{
FileOutputStream out = new FileOutputStream(myImage);
mbitmap_outputImage=BitmapFactory.decodeFile(mPath);
mbitmap_outputImage=Bitmap.createScaledBitmap(mbitmap_outputImage, 390, 310, true);
mbitmap_outputImage.compress(Bitmap.CompressFormat.PNG, 100, out);
img.setImageBitmap(mbitmap_outputImage);
out.flush();
out.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
@SuppressWarnings("deprecation")
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
public int uploadFile(String sourceFileUri) {
DataOutputStream dos = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
File sourceFile = new File(sourceFileUri);
if (!sourceFile.isFile()) {
dialog.dismiss();
Log.e("uploadFile", "Source File not exist :"
+ selectedImagePath);
runOnUiThread(new Runnable() {
public void run() {
messageText.setText("Source File not exist :"
+ selectedImagePath);
}
});
return 0;
}
else
{
try {
/* btns=uploadButton.getTag().toString();
System.out.println(btns);*/
String fileName = sourceFileUri;
File f = new File(selectedImagePath);
imgs= f.getName();
System.out.println(imgs);
upLoadServerUri = "http://www.asdf.com/web-service/imagetest.php?action=imagetest&image="+imgs;
// open a URL connection to the Servlet
FileInputStream fileInputStream = new FileInputStream(sourceFile);
URL url = new URL(upLoadServerUri);
System.out.println(url);
// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true); // Allow Inputs
conn.setDoOutput(true); // Allow Outputs
conn.setUseCaches(false); // Don't use a Cached Copy
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("ENCTYPE", "multipart/form-data");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
conn.setRequestProperty("image", imgs);
// conn.setRequestProperty("user_login_id", User_ID);
// conn.setRequestProperty("action", "addproduct");
// conn.setRequestProperty("version", "apps");
dos = new DataOutputStream(conn.getOutputStream());
// add parameters
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"type\""
+ lineEnd);
dos.writeBytes(lineEnd);
// assign value
// send image
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name='image';filename='"
+ imgs + "'" + lineEnd);
dos.writeBytes(lineEnd);
// create a buffer of maximum size
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// read file and write it into form...
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
// send multipart form data necesssary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// Responses from the server (code and message)
serverResponseCode = conn.getResponseCode();
String serverResponseMessage = conn.getResponseMessage();
Log.i("uploadFile", "HTTP Response is : "
+ serverResponseMessage + ": " + serverResponseCode);
if(serverResponseCode == 200){
runOnUiThread(new Runnable() {
@SuppressWarnings("deprecation")
public void run() {
try
{
DataInputStream dataIn = new DataInputStream(conn.getInputStream());
String inputLine;
while ((inputLine = dataIn.readLine()) != null)
{
result += inputLine;
System.out.println("Result : " + result);
}
//result=getJSONUrl(url); //<< get json string from server
//JSONObject jsonObject = new JSONObject(result);
JSONObject jobj = new JSONObject(result);
sta = jobj.getString("status");
msg = jobj.getString("msg");
System.out.println(sta + " >>>>>>> " + msg);
// new LoadImages().execute();
/* Intent intent=new Intent(PhotoUpload.this,PhotoView.class);
startActivity(intent);*/
}
catch (Exception e)
{
e.printStackTrace();
}
答案 0 :(得分:1)
你可以参考这个很好的教程&#34; Android Uploading Camera Image, Video to Server with Progress Bar&#34;
答案 1 :(得分:0)
尝试在标题中指定文件的长度。如果没有Content-Length标头,似乎某些服务器可能会拒绝该文件。 E.g:
conn.setRequestProperty("Content-Length", Integer.toString(fileInputStream.available()));