Android Studio - 快速Android网络库上传文件到服务器 - 错误

时间:2016-12-22 14:07:10

标签: php android android-networking

我正在尝试将从相机或图库中拍摄的图像上传到php服务器。为此,我使用了库Fast-Android-Networking

使用我的代码,我可以看到文件正在服务器中写入,但是它与0 B一起保存,onProgress函数也正在记录写入的正确字节。

对此有何帮助?如何使用此库正确地将从相机或库中获取的文件传递到服务器?

private File mFileTemp;

 btn_update.setOnClickListener(new OnClickListener() {
    // Start new list activity
    public void onClick(View v) {
        uploadFileNew(pref.getString("user_id", null));
    }
 });

    public void uploadFileNew(String frm_iduser) {

            String uploadUrl = "https://plus.example.com/apps/mobile/registered_users/uploadProfilePicAndroid.php?fileName=" + frm_iduser + ".png";

            AndroidNetworking.upload(uploadUrl)
                    .addMultipartFile("image",mFileTemp)
                    .addMultipartParameter("key","value")
                    .setTag("uploadTest")
                    .setPriority(Priority.HIGH)
                    .build()
                    .setUploadProgressListener(new UploadProgressListener() {
                        @Override
                        public void onProgress(long bytesUploaded, long totalBytes) {
                            // do anything with progress
                            Log.d("responce_app",String.valueOf(bytesUploaded));
                        }
                    })
                    .getAsJSONObject(new JSONObjectRequestListener() {
                        @Override
                        public void onResponse(JSONObject response) {
                            // do anything with response
                            Log.d("responce_app",String.valueOf(response));
                        }
                        @Override
                        public void onError(ANError error) {
                            // handle error
                            Log.d("responce_app",String.valueOf(error));
                            Log.d("responce_app","errorrrr");
                        }
                    });
        }

2 个答案:

答案 0 :(得分:1)

当我看到你的问题时,我正在编写确切的场景。我很高兴地告诉你,我刚刚完成了它。

这里是android代码:

@Override
    public void onClick(View view) {
        Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
        photoPickerIntent.setType("image/*");
        startActivityForResult(photoPickerIntent, 5000);
    }
public String getRealPathFromURI(Uri contentURI, Activity context) {
    String[] projection = { MediaStore.Images.Media.DATA };
    @SuppressWarnings("deprecation")
    Cursor cursor = context.managedQuery(contentURI, projection, null,
            null, null);
    if (cursor == null)
        return null;
    int column_index = cursor
            .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
    if (cursor.moveToFirst()) {
        String s = cursor.getString(column_index);
        // cursor.close();
        return s;
    }
    // cursor.close();
    return null;
}
@Override
protected void onActivityResult(int reqCode, int resultCode, Intent data) {
    super.onActivityResult(reqCode, resultCode, data);


if (resultCode == RESULT_OK) {
    try {
        final Uri selectedImageUri = data.getData();
        //final InputStream imageStream = //getContentResolver().openInputStream(selectedImageUri);
        //final Bitmap selectedImage = //BitmapFactory.decodeStream(imageStream);
        //imgUser.setImageBitmap(selectedImage);
   String imagepath = getRealPathFromURI(selectedImageUri,this);
    File imageFile = new File(imagepath);


                        AndroidNetworking.upload("http://test.sth.com/upload_file4.php")
                    .addMultipartFile("file", imageFile)
                     //.addMultipartParameter("key","value")
                    //.setTag("uploadTest")
                    .setPriority(Priority.HIGH)
                    .build()
                    .setUploadProgressListener(new UploadProgressListener() {
                        @Override
                        public void onProgress(long bytesUploaded, long totalBytes) {
                            // do anything with progress
                            tvProgress.setText((bytesUploaded / totalBytes)*100 + " %");
                        }
                    })
                    .getAsString(new StringRequestListener() {
                        @Override
                        public void onResponse(String response) {
                            Toast.makeText(MainActivity.this, response, Toast.LENGTH_SHORT).show();
                        }

                        @Override
                        public void onError(ANError anError) {
                            Toast.makeText(MainActivity.this, anError.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    });




    } catch (FileNotFoundException e) {
        e.printStackTrace();
        Toast.makeText(MainActivity.this, "Something went wrong", Toast.LENGTH_LONG).show();
    }

}else {
    Toast.makeText(MainActivity.this, "You haven't picked Image",Toast.LENGTH_LONG).show();
}
}

这是PHP代码:

<?php

$target_dir = "uploads/";
$target_file_name = $target_dir.basename($_FILES["file"]["name"]);
$response = array();

if(isset($_FILES["file"]))
{
if(move_uploaded_file($_FILES["file"]["tmp_name"],$target_file_name))
{
$success = true;
$message = "Uploaded!!!";
}
else
{
$success = false;
$message = "NOT Uploaded!!! _ Error While Uploading";
}
}
else{
$success = false;
$message = "missing field";
}
$response["success"] = $success;
$response["message"] = $message;
echo json_encode($response);
?>

注意:  1.将这些权限添加到您的清单:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
  1. 对于等于且高于23的API级别,您应该在运行时请求第二个权限。见this
  2. 不要忘记在服务器中创建一个文件夹,如下所示:
  3. CPanel

    1. 另请确保您已将此行添加到OnCreate

      AndroidNetworking.initialize(getApplicationContext());

答案 1 :(得分:0)

您的代码似乎没有任何问题。看起来你的服务器端代码有问题。

发布uploadProfilePicAndroid.php的内容,以便我们找到问题。

此外,无需在地址中传递文件名:

String uploadUrl = "https://plus.example.com/apps/mobile/registered_users/uploadProfilePicAndroid.php?fileName=" + frm_iduser + ".png"

在php代码中,您可以使用您在此处指定的名称"image"来访问该文件:

 .addMultipartFile("image",mFileTemp)

此外,每当您需要在请求中发送其他数据时,请使用库而不是地址,就像使用"key""value"一样:

 .addMultipartParameter("key","value")