java - Android使用GDK使用MultipartEntity上传图片

标签 java php android google-glass google-gdk

我正在使用 GDK 为 google glass 开发一个应用程序,我正在尝试使用 MultiPartEntity 上传我捕获的图像,但由于某种原因我无法让它工作我无法弄清楚,因为它没有返回任何错误。到目前为止,这就是我所在的位置。

Java

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

任何帮助将不胜感激。

最佳答案

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

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

关于java - Android使用GDK使用MultipartEntity上传图片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27684440/

相关文章:

java - JODA LocalDate 作为 Jersey 的 QueryParam

Zend Server CE 5.5 中带有 sha256 的 PHP crypt() 会截断提供的盐

PHP - 检查命名空间内是否存在全局类

android - BroadcastReceiver 不起作用?

android - GStreamer 通过 HTTPS 视频流传输 RTSP

java - 将参数传递给父类(super class)

java - elasticsearch中执行From/Size时的范围

java - android - 计时器不从零开始

php - 我将如何在一个查询中加入这两个查询?

java - Android 设备中等效的标签控件是什么?