Android使用GDK使用MultipartEntity上传图片

时间:2014-12-29 06:35:39

标签: java php android google-glass google-gdk

我使用GDK开发谷歌眼镜的应用程序,我试图使用MultiPartEntity上传我捕获的图像,但我无法让它工作由于某些原因我无法弄清楚,因为它没有返回任何错误。截至目前,这就是我的所在。

爪哇

String picturePath = data.getStringExtra(Intents.EXTRA_PICTURE_FILE_PATH);
final File pictureFile = new File(picturePath);

HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("SERVER PATH");

try {
    @SuppressWarnings("deprecation")
    MultipartEntity entity = new MultipartEntity();

    entity.addPart("type", new StringBody("photo"));
    entity.addPart("data", new FileBody(pictureFile));
    httppost.setEntity(entity);
    HttpResponse response = httpclient.execute(httppost);
    } catch (ClientProtocolException e) {
    } catch (IOException e) {
    }

PHP代码:     

$response = array();
$file_upload_url = 'UPLOAD PATH';


if (isset($_FILES['image']['name'])) {
$target_path = $target_path . basename($_FILES['image']['name']);

$email = isset($_POST['email']) ? $_POST['email'] : '';
$website = isset($_POST['website']) ? $_POST['website'] : '';

$response['file_name'] = basename($_FILES['image']['name']);
$response['email'] = $email;
$response['website'] = $website;

try {
    // Throws exception incase file is not being moved
    if (!move_uploaded_file($_FILES['image']['tmp_name'], $target_path)) {
        // make error flag true
        $response['error'] = true;
        $response['message'] = 'Could not move the file!';
    }

    // File successfully uploaded
    $response['message'] = 'File uploaded successfully!';
    $response['error'] = false;
    $response['file_path'] = $file_upload_url . basename($_FILES['image']['name']);
} catch (Exception $e) {
    // Exception occurred. Make error flag true
    $response['error'] = true;
    $response['message'] = $e->getMessage();
}
} else {
// File parameter is missing
$response['error'] = true;
$response['message'] = 'Not received any file!';
}

echo json_encode($response);
?>

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:5)

这是我的代码。它对我有用。您可以使用此代码发送带有进度条的参数和文件。

public class SendFile extends AsyncTask<String, Integer, Integer> {

    private Context conT;
    private ProgressDialog dialog;
    private String SendUrl = "";
    private String SendFile = "";
    private String Parameters = "";
    private String result;
    public File file;

    SendFile(Context activity, String url, String filePath, String values) {
        conT = activity;
        dialog = new ProgressDialog(conT);
        SendUrl = url;
        SendFile = filePath;
        Parameters = Values;
    }

    @Override
    protected void onPreExecute() {
        file = new File(SendFile);
        dialog.setMessage("Please Wait..");
        dialog.setCancelable(false);
        dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        dialog.setMax((int) file.length());
        dialog.show();
    }

    @Override
    protected Integer doInBackground(String... params) {
        HttpURLConnection connection = null;
        DataOutputStream outputStream = null;
        InputStream inputStream = null;
        String twoHyphens = "--";
        String boundary = "*****"
                + Long.toString(System.currentTimeMillis()) + "*****";
        String lineEnd = "\r\n";

        int bytesRead, bytesAvailable, bufferSize;
        byte[] buffer;
        int maxBufferSize = 1 * 512;

        String[] q = SendFile.split("/");
        int idx = q.length - 1;
        try {

            FileInputStream fileInputStream = new FileInputStream(file);

            URL url = new URL(SendUrl);
            connection = (HttpURLConnection) url.openConnection();
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setUseCaches(false);

            connection.setRequestMethod("POST");
            connection.setRequestProperty("Connection", "Keep-Alive");
            connection.setRequestProperty("User-Agent",
                    "Android Multipart HTTP Client 1.0");
            connection.setRequestProperty("Content-Type",
                    "multipart/form-data; boundary=" + boundary);

            outputStream = new DataOutputStream(
                    connection.getOutputStream());
            outputStream.writeBytes(twoHyphens + boundary + lineEnd);
            outputStream
                    .writeBytes("Content-Disposition: form-data; name=dosya; filename=\""
                            + q[idx] + "\"" + lineEnd);
            outputStream.writeBytes("Content-Type: image/jpg" + lineEnd);
            outputStream.writeBytes("Content-Transfer-Encoding: binary"
                    + lineEnd);
            outputStream.writeBytes(lineEnd);

            bytesAvailable = fileInputStream.available();
            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            buffer = new byte[bufferSize];

            bytesRead = fileInputStream.read(buffer, 0, bufferSize);
            int boyut = 0;
            while (bytesRead > 0) {
                boyut += bytesRead;
                outputStream.write(buffer, 0, bufferSize);
                bytesAvailable = fileInputStream.available();
                bufferSize = Math.min(bytesAvailable, maxBufferSize);
                bytesRead = fileInputStream.read(buffer, 0, bufferSize);
                dialog.setProgress(boyut);
            }

            outputStream.writeBytes(lineEnd);

            String[] posts = Bilgiler.split("&");
            int max = posts.length;
            for (int i = 0; i < max; i++) {
                outputStream.writeBytes(twoHyphens + boundary + lineEnd);
                String[] kv = posts[i].split("=");
                outputStream
                        .writeBytes("Content-Disposition: form-data; name=\""
                                + kv[0] + "\"" + lineEnd);
                outputStream.writeBytes("Content-Type: text/plain"
                        + lineEnd);
                outputStream.writeBytes(lineEnd);
                outputStream.writeBytes(kv[1]);
                outputStream.writeBytes(lineEnd);
            }

            outputStream.writeBytes(twoHyphens + boundary + twoHyphens
                    + lineEnd);
            inputStream = connection.getInputStream();
            result = this.convertStreamToString(inputStream);
            Log.v("TAG","result:"+result);
            fileInputStream.close();
            inputStream.close();
            outputStream.flush();
            outputStream.close();
        } catch (Exception e) {

        }

        return null;
    }

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

    @Override
    protected void onPostExecute(Integer result1) {
        dialog.dismiss();
    };

    private String convertStreamToString(InputStream is) {
        BufferedReader reader = new BufferedReader(
                new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();

        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }

如果你要发送给PHP,你可以使用这个

<?php 
     $file_path = "test/";
     $username= $_POST["username"];
     $password= $_POST["password"];
     $file_path = $file_path . basename( $_FILES['uploaded_file']['name']);
     if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $file_path)) {
         echo "success";
     } else{
         echo "fail";
     }

?>

编辑 - 2:

您可以将此AsyncTask称为:

        String FormData = "username=" + Session.getUsername()
                + "&password=" + Session.getPassword() ;
        SendFile SendIt= new SendFile(this, upLoadServerUri, filePath,FormData);
        SendIt.execute();