简体   繁体   English

无法将Android文件上传到服务器(用PHP编写)

[英]Android file upload to server (written in PHP) not working

I am new to PHP. 我是PHP新手。 I am building an android project which needs to upload images to my server. 我正在构建一个需要将图像上传到我的服务器的android项目。 The problem i am having is that when I send just a key and a value (no file) to the server, it works perfectly fine. 我遇到的问题是,当我仅将密钥和值(无文件)发送到服务器时,它就可以正常工作。 However, as soon as I try to send a file, the superglobals $_POST and $_FILES in php are empty! 但是,一旦我尝试发送文件,php中的superglobals $ _POST和$ _FILES为空! The file sent is very small, so its not go to do with the file_max_upload_size. 发送的文件非常小,因此与file_max_upload_size无关。 The file is not corrupted. 该文件未损坏。 I think it is something to do with the encoding of of the InputStream sent by the app on the android emulator. 我认为这与Android模拟器上的应用发送的InputStream的编码有关。 My code is below: 我的代码如下:

Java code in the app that sends the image along with a key-value pair: 应用程序中的Java代码,用于将图像与键值对一起发送:

    public Future<JSONObject> asyncSendPOSTRequest(String URL, Map<String, String> params, Map<String, Pair<String,InputStream>> files) throws InterruptedException, ExecutionException, JSONException, UnsupportedEncodingException {  
            HttpPost request = new HttpPost(URL);
            MultipartEntityBuilder multipartEntity = MultipartEntityBuilder.create();
            if(params!=null) {
                for(String key : params.keySet()) {
                    multipartEntity.addTextBody(key, params.get(key), ContentType.TEXT_PLAIN);
                }
            }
            if(files!=null) {
                for(String key : files.keySet()) {
                    multipartEntity.addPart(key, new InputStreamBody(files.get(key).second,ContentType.MULTIPART_FORM_DATA, files.get(key).first));
                }
            }
            request.setEntity(multipartEntity.build());


Future<JSONObject> future = threadPool.submit(new executeRequest(request));
        return future;
    }
//Thread to communicate with server.
    private class executeRequest implements Callable<JSONObject> {

        HttpRequestBase request;

        public executeRequest(HttpRequestBase request) {
            this.request = request;
        }
        @Override
        public JSONObject call() throws Exception {
            HttpResponse httpResponse = httpClient.execute(request);
            BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent()));
            StringBuilder stringReply = new StringBuilder();
            String replyLine;
            while ((replyLine = reader.readLine()) != null) {
                stringReply.append(replyLine);
            }
            return new JSONObject(stringReply.toString());
        }   
    }

The code on the server: 服务器上的代码:

#!/usr/bin/php
<?php
$uploads_dir = __DIR__ . '/uploads';
$status = -1;
    if ($_FILES["picture"]["error"] == UPLOAD_ERR_OK) {
        $tmp_name = $_FILES["picture"]["tmp_name"];
        $name = $_FILES["picture"]["name"];
        $status = move_uploaded_file($tmp_name, "$uploads_dir/$name");
    }
$response["status"] = $status;
$response["user_id"] = $_POST["user_id"];
$response["name"] =  $name;
$response["extension"] = end (explode(".", $name));
echo json_encode($response);
?>

您设置了错误的数据类型的可能问题

enctype="multipart/form-data"
public class Helpher extends AsyncTask<String, Void, String> {
    Context context;
    JSONObject json;
    ProgressDialog dialog;
    int serverResponseCode = 0;
    DataOutputStream dos = null;
    FileInputStream fis = null;
    BufferedReader br = null;


    public Helpher(Context context) {
        this.context = context;
    }

    protected void onPreExecute() {

        dialog = ProgressDialog.show(Main2Activity.this, "ProgressDialog", "Wait!");
    }

    @Override
    protected String doInBackground(String... arg0) {

        try {
            File f = new File(arg0[0]);
            URL url = new URL("http://localhost:8888/imageupload.php");
            int bytesRead;
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);

            String contentDisposition = "Content-Disposition: form-data; name=\"keyValueForFile\"; filename=\""
                    + f.getName() + "\"";
            String contentType = "Content-Type: application/octet-stream";


            dos = new DataOutputStream(conn.getOutputStream());
            fis = new FileInputStream(f);

            dos.writeBytes(SPACER + BOUNDARY + NEW_LINE);
            dos.writeBytes("Content-Disposition: form-data; name=\"parameterKey\""
                    + NEW_LINE);
            dos.writeBytes(NEW_LINE);
            dos.writeBytes("parameterValue" + NEW_LINE);

            dos.writeBytes(SPACER + BOUNDARY + NEW_LINE);
            dos.writeBytes(contentDisposition + NEW_LINE);
            dos.writeBytes(contentType + NEW_LINE);
            dos.writeBytes(NEW_LINE);
            byte[] buffer = new byte[MAX_BUFFER_SIZE];
            while ((bytesRead = fis.read(buffer)) != -1) {
                dos.write(buffer, 0, bytesRead);
            }
            dos.writeBytes(NEW_LINE);
            dos.writeBytes(SPACER + BOUNDARY + SPACER);
            dos.flush();

            int responseCode = conn.getResponseCode();
            if (responseCode != 200) {
                Log.w(TAG,
                        responseCode + " Error: " + conn.getResponseMessage());
                return null;
            }

            br = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = br.readLine()) != null) {
                sb.append(line + "\n");
            }
            Log.d(TAG, "Sucessfully uploaded " + f.getName());

        } catch (MalformedURLException e) {
        } catch (IOException e) {
        } finally {
            try {
                dos.close();
                if (fis != null)
                    fis.close();
                if (br != null)
                    br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return String.valueOf(serverResponseCode);
    }


    @Override
    protected void onPostExecute(String result) {
        dialog.dismiss();

    }

}

This is the AsyncTask "Helpher" class used for upload image from Android. 这是AsyncTask“ Helpher”类,用于从Android上传图像。 To call this class use like syntax below. 要调用此类,请使用以下语法。

new Main2Activity.Helpher(this).execute(fileUri.getPath(),parameterValue);

Here fileUri.getPath() local image location. 在这里,fileUri.getPath()本地映像位置。 If you want to see the server response value is avilable in " StringBuilder sb" you can print sb value 如果要在“ StringBuilder sb”中看到服务器响应值可用,则可以打印sb值

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM