Android Studio - Fast Android Networking Library Upload File to server - error

爷,独闯天下 提交于 2020-03-27 05:40:08

问题


I am trying to Upload an image taken from Camera or Gallery to a php server. To do so I am using the library Fast-Android-Networking

With my code I can see the file is writing in the server however, it is saved with 0 B, also the onProgress function is logging out the correct bytes written.

Any help with This? How can I properly pass the file taken from the camera or gallery to the server using this library?

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");
                        }
                    });
        }

回答1:


I was coding the exact scenario when I saw your question. And I am happy to tell you that I have just done it.

Here's the android code:

@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();
}
}

Here's the php code:

<?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);
?>

Note: 1.Add these permissions to your manifest:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
  1. For API level equal and higher than 23 you should ask for second permission at run time. see this.
  2. Do not forget to create a folder in your server like below:

  1. Also be sure you have added this line to your OnCreate:

    AndroidNetworking.initialize(getApplicationContext());




回答2:


There seems to be nothing wrong with your code. Looks like your server-side code is at fault here.

Post the contents of uploadProfilePicAndroid.php so we can find the problem.

Also, there is no need to pass the file name in the address:

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

In the php code you can access the file using the name "image" you specified here:

 .addMultipartFile("image",mFileTemp)

Furthermore, whenever you DO need to send additional data in your request, do it using the library and not the address, as you did with "key" and "value":

 .addMultipartParameter("key","value")


来源:https://stackoverflow.com/questions/41285015/android-studio-fast-android-networking-library-upload-file-to-server-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!