【问题标题】:Image is not uploading to server using Laravel API while working with core PHP API使用核心 PHP API 时,图像未使用 Laravel API 上传到服务器
【发布时间】:2017-02-15 10:17:21
【问题描述】:

我正在使用 Laravel 编写的 Web 服务使用 Volley 库上传图像。 Android代码是:显示500 internal server error

public class MainActivity extends AppCompatActivity implements View.OnClickListener{

    private Button buttonChoose;
    private Button buttonUpload;
    private ImageView imageView;
    private EditText editTextName;
    private Bitmap bitmap;
    private int PICK_IMAGE_REQUEST = 1;
    private String KEY_IMAGE = "image";
    private String KEY_NAME = "name";
    private String UPLOAD_URL = "http://192.168.1.9/volley/upload.php";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        buttonChoose = (Button)findViewById(R.id.buttonChoose);
        buttonUpload = (Button)findViewById(R.id.buttonUpload);
        editTextName = (EditText)findViewById(R.id.editText);
        imageView = (ImageView)findViewById(R.id.imageView);
        buttonChoose.setOnClickListener(this);
        buttonUpload.setOnClickListener(this);
    }
    private void showFileChooser() {
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
            Uri filePath = data.getData();
            try {
                //Getting the Bitmap from Gallery
                bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
                //Setting the Bitmap to ImageView
                imageView.setImageBitmap(bitmap);
            }
            catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public String getStringImage(Bitmap bmp) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bmp.compress(Bitmap.CompressFormat.PNG, 100, baos);
        byte[] imageBytes = baos.toByteArray();
        String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
        return encodedImage;
    }

    private void uploadImage() {
        //Showing the progress dialog
        final ProgressDialog loading = ProgressDialog.show(this,"Uploading...","Please wait...",false,false);
        StringRequest stringRequest = new StringRequest(Request.Method.POST, UPLOAD_URL,
            new Response.Listener<String>() {
            @Override
                public void onResponse(String s) {
                //Disimissing the progress dialog
                loading.dismiss();
                //Showing toast message of the response
                Toast.makeText(MainActivity.this, KEY_IMAGE , Toast.LENGTH_LONG).show();
            }
        },
            new Response.ErrorListener() {
            @Override
                public void onErrorResponse(VolleyError volleyError) {
                //Dismissing the progress dialog
                loading.dismiss();

                //Showing toast
                Toast.makeText(MainActivity.this, volleyError.toString(), Toast.LENGTH_LONG).show();
            }
        }){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
            //Converting Bitmap to String
            String image = getStringImage(bitmap);

            //Getting Image Name
            String name = editTextName.getText().toString().trim();

            //Creating parameters
            Map<String,String> params = new Hashtable<String, String>();

            //Adding parameters
            params.put(KEY_IMAGE, image);
            params.put(KEY_NAME, name);

            //returning parameters
            return params;
        }
        };

        //Creating a Request Queue
        RequestQueue requestQueue = Volley.newRequestQueue(this);

        //Adding request to the queue
        requestQueue.add(stringRequest);
    }

    @Override
    public void onClick(View v) {

        if (v == buttonChoose) {
            showFileChooser();
        }

        if (v == buttonUpload) {
            uploadImage();
        }
    }
}

Laravel API 代码是

$filename = Input::get('name');
$imageStr = $request->input('image');
$decodeImage = base64_decode($imageStr);
//        $image = fwrite($decodeImage);
if ($request->hasFile('image')) {
    $filename = $request->file('image')->getClientOriginalName();
    $moveImage = $request->file('image')->move('uploads/images', $filename);
}
$image = new Image();
$image->photo = "uploads/images/".$filename;
$image->name = Input::get('name');
$result = $image->save();
if ($result){
    return response()->json('yes');
}
else{
    return response()->json('no');
}

但是当我使用核心 PHP API 图像上传成功。 请帮助查找问题,核心PHP代码是:

if ($_SERVER['REQUEST_METHOD'] == 'POST') {

    $image = $_POST['image'];
    $name = $_POST['name'];

    require_once('dbConnect.php');

    $sql = "SELECT id FROM volley ORDER BY id ASC";

    $res = mysqli_query($con, $sql);

    $id = 2;

    while ($row = mysqli_fetch_array($res)) {
        $id = $row['id'];
    }

    $path = "uploads/$name.png";

    $actualpath = "http://192.168.2.113/volley/$path";

    $sql = "INSERT INTO image (photo,name) VALUES ('$actualpath','$name')";

    if (mysqli_query($con, $sql)) {
        file_put_contents($path, base64_decode($image));
        echo "Successfully Uploaded";
    }

    mysqli_close($con);
}
else {
    echo "Error";
}

【问题讨论】:

    标签: php android laravel android-volley


    【解决方案1】:

    问题来了

    if ($request->hasFile('image')) {
        $filename = $request->file('image')->getClientOriginalName();
        $moveImage = $request->file('image')->move('uploads/images', $filename);
    }
    

    因为您正在检查请求是否包含文件,并且您正在发送不是文件的 base64 编码数据,因此您的文件没有上传

    这是工作代码

    $filename = Input::get('name');
    $imageStr = $request->input('image');
    
    if (!empty($imageStr)) {
        file_put_contents('YOUR_UPLOAD_PATH/'.$filename.'.png', base64_decode($imageStr));
    }
    $image = new Image();
    $image->photo = "YOUR_UPLOAD_PATH/".$filename.'.png';
    $image->name = $filename.'.png';
    $result = $image->save();
    if ($result){
        return response()->json('yes');
    }
    else{
        return response()->json('no');
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-12-21
      • 2019-03-04
      • 2022-07-25
      • 2019-06-29
      • 1970-01-01
      • 2019-01-25
      • 1970-01-01
      相关资源
      最近更新 更多