无法将图像上传到服务器

时间:2016-12-10 08:47:18

标签: android

我想以图像格式将图像上传到数据库(c面板)。为此,我首先从图库中选择图像或捕获图像,在图像视图中设置图像并尝试将图像作为输入传递参数通过api。但是无法发送图像文件。

选择图片

@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    switch (requestCode) {
        case Utility.MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE:
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                if(userChoosenTask.equals("Take Photo"))
                    cameraIntent();
                else if(userChoosenTask.equals("Choose from Library"))
                    galleryIntent();
            } else {
                //code for deny
            }
            break;
    }
}

private void selectImage() {
    final CharSequence[] items = { "Take Photo", "Choose from Library", "Cancel" };

    AlertDialog.Builder builder = new AlertDialog.Builder(ProfileActivity.this);
    builder.setTitle("Add Photo!");
    builder.setItems(items, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int item) {
            boolean result=Utility.checkPermission(ProfileActivity.this);

            if (items[item].equals("Take Photo")) {
                userChoosenTask ="Take Photo";
                if(result)
                    cameraIntent();

            } else if (items[item].equals("Choose from Library")) {
                userChoosenTask ="Choose from Library";
                if(result)
                    galleryIntent();

            } else if (items[item].equals("Cancel")) {
                dialog.dismiss();
            }
        }
    });
    builder.show();
}

private void galleryIntent()
{
    Intent intent = new Intent();
    intent.setType("image/*");
    intent.setAction(Intent.ACTION_GET_CONTENT);
    startActivityForResult(Intent.createChooser(intent, "Select File"),SELECT_FILE);
}

private void cameraIntent()
{
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    startActivityForResult(intent, REQUEST_CAMERA);
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (resultCode == Activity.RESULT_OK) {
        if (requestCode == SELECT_FILE)
            onSelectFromGalleryResult(data);
        else if (requestCode == REQUEST_CAMERA)
            onCaptureImageResult(data);
    }
}

private void onCaptureImageResult(Intent data) {
    Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes);

    File destination = new File(Environment.getExternalStorageDirectory(),
            System.currentTimeMillis() + ".jpg");

    FileOutputStream fo;
    try {
        destination.createNewFile();
        fo = new FileOutputStream(destination);
        fo.write(bytes.toByteArray());
        fo.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    iv_profile.setImageBitmap(thumbnail);
    ProfileImageAPI api = new ProfileImageAPI(this,this);
    api.processProfileImage(AppController.getInstance().userId,destination,"photo.jpg");

}

@SuppressWarnings("deprecation")
private void onSelectFromGalleryResult(Intent data) {

    Bitmap bm=null;
    if (data != null) {
        try {
            bm = MediaStore.Images.Media.getBitmap(getApplicationContext().getContentResolver(), data.getData());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    iv_profile.setImageBitmap(bm);
}

}

api.php

function process_updateUserProfileImage()
{
    $user_id         = isset($_REQUEST['user_id'])?$_REQUEST['user_id']:"";

    if($user_id == "" ){
        echo json_encode(array("error"=>"1", "error_type"=>"user updateUserProfile", "error_no" => "1009", "error_message" => "Input validation"));
        exit;
    }

             $file_name = "";
             $file_url = "";

             if($_FILES["profile_image"]["name"]!="")
             { 
                 $file_name=time().$_FILES["profile_image"]["name"];
                 $tmp_name=$_FILES["profile_image"]["tmp_name"];
                 $file_type=$_FILES['profile_image']['type'];
                 $file_size=$_FILES['profile_image']['size'];
                 $upload_dir="../profile_image/";

                 fileUpload($upload_dir,$file_name,$tmp_name,$file_size,"image");
                 MakeThumbnail($upload_dir, $file_name ,100,100);   

                 $file_url = SITE_URL.'profile_image/'.$file_name;
             }

            $sql = "update user set
                `profile_image`     = '".trim($file_url)."'
                 where user_id      = '".$user_id."'
                ";

            $rs = mysql_query($sql);


            /*$userArr = array("success"=>"1", "sucess_type"=>"user registration", "success_message" => "User successfully registered");*/
            $userInfo = mysql_fetch_array(mysql_query("select * from user where user_id = ".$user_id));


            $userArr = array();

            $userArr =  array('user_id'=>$userInfo['user_id'],'profile_image'=>$userInfo['profile_image'],"success_message" => "profile image updated successfully");
            echo json_encode($userArr);
            exit();

}

ProfileImageApi类

public class ProfileImageAPI extends BaseAPI {

private Context mContext;
private NetworkCallback mCallback;

public ProfileImageAPI(Context context, NetworkCallback callback) {
    super(context);
    this.mContext = context;
    this.mCallback = callback;
}
public void processProfileImage(final String userId, final File profileImg, final String imgName){
    showProgressDialog();
    StringRequest strReq = new StringRequest(Request.Method.POST,
            ApiUtil.BASE_EDIT_PROFILE_IMAGE, new Response.Listener<String>() {

        @Override
        public void onResponse(String response) {
            Log.d(ApiUtil.TAG_EDIT_PROFILE_IMAGE, response.toString());

            mCallback.updateScreen(response,ApiUtil.TAG_EDIT_PROFILE_IMAGE);
            hideProgressDialog();
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            VolleyLog.d(ApiUtil.TAG_EDIT_PROFILE_IMAGE, "Error: " + error.getMessage());
            mCallback.updateScreen("ERROR",ApiUtil.TAG_EDIT_PROFILE_IMAGE);
            hideProgressDialog();
        }
    }){
        @Override
        protected Map<String, String> getParams() {
            Map<String, String> params = new HashMap<String, String>();
            params.put(ApiUtil.PARAM_USER_ID,userId);
            params.put(ApiUtil.PARAM_PROFILE_IMG,profileImg.toString());
            params.put(ApiUtil.PARAM_IMG_NAME,imgName);
            return params;
        }
    };
    // Adding request to request queue
    AppController ctrl = AppController.getInstance();
    ctrl.addToRequestQueue(strReq, ApiUtil.TAG_EDIT_PROFILE_IMAGE);
}

}

1 个答案:

答案 0 :(得分:0)

您用于api调用的库。 1.改造 2. Okhttp。

改造MultiPartWebservice:"Retrofit" multiple images attached in one multipart request OKHttp MultiPartWebservice: how to use okhttp to upload a file?