Resposte 200 из PHP после отправки изображения из Android-студии - PullRequest
0 голосов
/ 03 декабря 2018

Мне нужно отправить изображение с Android в папку на сервере с использованием Java-PHP. Моя проблема - нет загрузки изображения и ответа 200 с сервера, индикатор выполнения без проблем переходит на 100, и, если возможно, как я могу передать изображение данных из imageview в код, спасибо,мой код php в файле uploadphp.php

<?php
$base=$_REQUEST['image'];
 $binary=base64_decode($base);
header('Content-Type: bitmap; charset=utf-8');
$file = fopen('uploaded_image.jpg', 'wb');
fwrite($file, $binary);
fclose($file);
echo 'Image upload complete!!, Please check your php file directory……';?>

мой класс кода Java AsyncTask

private class BackgroundUploader extends AsyncTask<Void, Integer, String> {

    private ProgressDialog progressDialog;
    private String url;
    private File file;


    public BackgroundUploader(String url, File file) {
        this.url = url;
        this.file = file;
    }
    @Override
    protected void onPreExecute() {
        progressDialog = new ProgressDialog(MainActivity.this);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressDialog.setMessage("Uploading...");
        // progressDialog.setCancelable(false);
        progressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                cancel(true);
            }
        });
        //   progressDialog.setMax((int) file.length());
        progressDialog.setMax(100);
        progressDialog.show();
    }

    @Override
    protected String doInBackground(Void... v) {
        String res = "fail";
        HttpURLConnection.setFollowRedirects(false);
        HttpURLConnection connection = null;
        //  String fileName = file.getName();
        String fileName = "";
        if (file.getName().toLowerCase().endsWith(".jpg")) {
            fileName = System.currentTimeMillis() + ".jpg";
        } else if (file.getName().toLowerCase().endsWith(".png")) {
            fileName = System.currentTimeMillis() + ".png";
        } else if (file.getName().toLowerCase().endsWith(".bmp")) {
            fileName = System.currentTimeMillis() + ".bmp";
        }
        try {
            connection = (HttpURLConnection) new URL(url).openConnection();
            connection.setRequestMethod("POST");
            String boundary = "---------------------------boundary";
            String tail = "\r\n--" + boundary + "--\r\n";
            connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
            connection.setDoOutput(true);

            String metadataPart = "--" + boundary + "\r\n"
                    + "Content-Disposition: form-data; name=\"metadata\"\r\n\r\n"
                    + "" + "\r\n";

            String fileHeader1 = "--" + boundary + "\r\n"
                    + "Content-Disposition: form-data; name=\"uploaded_file\"; filename=\""
                    + fileName + "\"\r\n"
                    + "Content-Type: application/octet-stream\r\n"
                    + "Content-Transfer-Encoding: binary\r\n";

            long fileLength = file.length() + tail.length();
            String fileHeader2 = "Content-length: " + fileLength + "\r\n";
            String fileHeader = fileHeader1 + fileHeader2 + "\r\n";
            String stringData = metadataPart + fileHeader;

            long requestLength = stringData.length() + fileLength;
            connection.setRequestProperty("Content-length", "" + requestLength);
            connection.setFixedLengthStreamingMode((int) requestLength);
            connection.connect();

            DataOutputStream out = new DataOutputStream(connection.getOutputStream());
            out.writeBytes(stringData);
            out.flush();

            int progress = 0;
            int bytesRead = 0;
            byte buf[] = new byte[1024];
            BufferedInputStream bufInput = new BufferedInputStream(new FileInputStream(file));
            while ((bytesRead = bufInput.read(buf)) != -1) {
                // write output
                out.write(buf, 0, bytesRead);
                out.flush();
                progress += bytesRead;
                // update progress bar
                publishProgress((int) ((progress * 100) / (file.length())));
                //  publishProgress(progress);
            }

            // Write closing boundary and close stream
            out.writeBytes(tail);
            out.flush();
            out.close();
            if (connection.getResponseCode() == 200 || connection.getResponseCode() == 201) {

            }
        } catch (Exception e) {
            // Exception
        } finally {
            if (connection != null) connection.disconnect();
        }
        return res;
    }

    @Override
    protected void onProgressUpdate(Integer... progress) {
        progressDialog.setProgress((int) (progress[0]));
    }

    @Override
    protected void onCancelled() {
        Toast.makeText(MainActivity.this, "Upload cancel", Toast.LENGTH_LONG).show();
    }

    @Override
    protected void onPostExecute(String v) {
        if (progressDialog.isShowing()) {
            progressDialog.dismiss();
        }
    }
}

любая помощь спасибо

1 Ответ

0 голосов
/ 03 декабря 2018

Похоже, проблема с вашим PHP-кодом, попробуйте

<?php

if (is_uploaded_file($_FILES['uploaded_file']['tmp_name'])) {
    $uploads_dir = './';
    $tmp_name = $_FILES['uploaded_file']['tmp_name'];
    $pic_name = $_FILES['uploaded_file']['name'];
    move_uploaded_file($tmp_name, $uploads_dir.$pic_name);
}
else{
       echo "File not uploaded successfully.";
}
...