doupishan3309 2015-01-07 01:56
浏览 65
已采纳

POST后的图像数据丢失(从Android应用程序到php服务器)

I am trying to upload an img from an android phone to a php server.

But when it is uploaded its data is lost(the file exist but has 0 bytes)

I dont know if the problem is on the php side or the android side.

Here is the code I use uploadenter code here

<?php
error_reporting(E_ALL);
if(isset($_POST['ImageName'])){
$imgname = $_POST['ImageName'];
$imsrc = base64_decode($_POST['base64']);
$fp = fopen($imgname, 'w');
fwrite($fp, $imsrc);
if(fclose($fp)){
    echo "Image uploaded";
}else{
    echo "Error uploading image";
}
}
?>

I am not getting any errors anywhere

heres my java

package com.cfaulk.frankensync;

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Base64;

import android.view.Menu; import android.view.MenuItem;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
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.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;


public class MainActivity extends ActionBarActivity {

Button btpic, btnup;
private Uri fileUri;
String picturePath;
Uri selectedImage;
Bitmap photo;
String ba1;
public static String URL = "http://www.dankeedoodle.com/frankensync/upload.php";
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.mainactivity);

    btpic = (Button) findViewById(R.id.cpic);
    btpic.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            clickpic();
        }
    });

    btnup = (Button) findViewById(R.id.up);
    btnup.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            upload();
        }
    });
}

private void upload() {
    // Image location URL
    Log.e("path", "----------------" + picturePath);

    // Image
    Bitmap bm = BitmapFactory.decodeFile(picturePath);
    ByteArrayOutputStream bao = new ByteArrayOutputStream();
    bm.compress(Bitmap.CompressFormat.JPEG, 90, bao);
    byte[] ba = bao.toByteArray();
    //ba1 = Base64.encode(ba);
    int flag = 0; // you can pass the default 0 = Base64.DEFAULT
    String ba1 = Base64.encodeToString(ba, flag);

    Log.e("base64", "-----" + ba1);

    // Upload image to server
    new uploadToServer().execute();

}

private void clickpic() {
    // Check Camera
    if (getApplicationContext().getPackageManager().hasSystemFeature(
            PackageManager.FEATURE_CAMERA)) {
        // Open default camera
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);

        // start the image capture Intent
        startActivityForResult(intent, 100);

    } else {
        Toast.makeText(getApplication(), "Camera not supported", Toast.LENGTH_LONG).show();
    }
}

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == 100 && resultCode == RESULT_OK) {

        selectedImage = data.getData();
        photo = (Bitmap) data.getExtras().get("data");

        // Cursor to get image uri to display

        String[] filePathColumn = {MediaStore.Images.Media.DATA};
        Cursor cursor = getContentResolver().query(selectedImage,
                filePathColumn, null, null, null);
        cursor.moveToFirst();

        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        picturePath = cursor.getString(columnIndex);
        cursor.close();

        Bitmap photo = (Bitmap) data.getExtras().get("data");
        ImageView imageView = (ImageView) findViewById(R.id.Imageprev);
        imageView.setImageBitmap(photo);
    }
}

public class uploadToServer extends AsyncTask<Void, Void, String> {

    private ProgressDialog pd = new ProgressDialog(MainActivity.this);
    protected void onPreExecute() {
        super.onPreExecute();
        pd.setMessage("Wait image uploading!");
        pd.show();
    }

    @Override
    protected String doInBackground(Void... params) {

        ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        nameValuePairs.add(new BasicNameValuePair("base64", ba1));
        nameValuePairs.add(new BasicNameValuePair("ImageName", System.currentTimeMillis() + ".jpg"));
        try {
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(URL);
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            HttpResponse response = httpclient.execute(httppost);
            String st = EntityUtils.toString(response.getEntity());
            Log.v("log_tag", "In the try Loop" + st);

        } catch (Exception e) {
            Log.v("log_tag", "Error in http connection " + e.toString());
        }
        return "Success";

    }

    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        pd.hide();
        pd.dismiss();
    }
}

}

  • 写回答

1条回答 默认 最新

  • dqybjj3497 2015-01-07 12:39
    关注

    You have declared Activity member String ba1 and you are uploading content of that string.

    However, in your upload() function you have line String ba1 = Base64.encodeToString(ba, flag); That declares another string named ba1 and that string is the one that contains content of your image.

    You should change that line to ba1 = Base64.encodeToString(ba, flag); to use Activity variable ba1

    You can confirm that Android side is not working properly by inspecting value of $_POST['base64'] variable.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 plotBAPC画图出错
  • ¥30 关于#opencv#的问题:使用大疆无人机拍摄水稻田间图像,拼接成tif图片,用什么方法可以识别并框选出水稻作物行
  • ¥15 Python卡尔曼滤波融合
  • ¥20 iOS绕地区网络检测
  • ¥15 python验证码滑块图像识别
  • ¥15 根据背景及设计要求撰写设计报告
  • ¥20 能提供一下思路或者代码吗
  • ¥15 用twincat控制!
  • ¥15 请问一下这个运行结果是怎么来的
  • ¥15 单通道放大电路的工作原理