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.

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

报告相同问题?

悬赏问题

  • ¥35 平滑拟合曲线该如何生成
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 自己瞎改改,结果现在又运行不了了
  • ¥15 链式存储应该如何解决
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站