簡體   English   中英

如何使用multipart將REQUEST值添加到HTTP POST方法,以將文件上傳到Android中的PHP服務器?

[英]How do I add REQUEST values to an HTTP POST method using multipart to upload a file to a PHP server in Android?

因此,我正在嘗試將文件上傳到我的PHP服務器。 我在網上找到了一些行之有效的代碼,但我還需要包含諸如用戶身份驗證之類的值以及應在文件上載文件的位置。 我對HTTP通訊比較陌生,下面發現的代碼使用以前從未聽說過的術語/代碼,特別是multipart/form-data Content-TypeContent-Disposition 因此,如果有人可以告訴我如何包括我需要的值,提供完全不同的方法,或者像我五歲一樣向我解釋這三個術語,我將不勝感激。 這是我的代碼:

public static void upload(String path, String section, Context c){
    Log.i("path", path);
    HttpURLConnection conn = null;
    DataOutputStream dos = null;
    DataInputStream inStream = null;

    String lineEnd = "\r\n";
    String twoHyphens = "--";
    String boundary = "*****";
    int bytesRead, bytesAvailable, bufferSize;
    byte[] buffer;
    int maxBufferSize = 1 * 1024 * 1024;
    String responseFromServer = "";
    String urlString = c.getString(R.string.server) + "upload.php";
    try {
        // ------------------ CLIENT REQUEST
        FileInputStream fileInputStream = new FileInputStream(new File(
                path));
        // open a URL connection to the Servlet
        URL url = new URL(urlString);
        // Open a HTTP connection to the URL
        conn = (HttpURLConnection) url.openConnection();
        // Allow Inputs
        conn.setDoInput(true);
        // Allow Outputs
        conn.setDoOutput(true);
        // Don't use a cached copy.
        conn.setUseCaches(false);
        // Use a post method.
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
        dos = new DataOutputStream(conn.getOutputStream());
        dos.writeBytes(twoHyphens + boundary + lineEnd);
        dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\""
                + path + "\"" + lineEnd);
        dos.writeBytes(lineEnd);
        // create a buffer of maximum size
        bytesAvailable = fileInputStream.available();
        bufferSize = Math.min(bytesAvailable, maxBufferSize);
        buffer = new byte[bufferSize];
        // read file and write it into form...
        bytesRead = fileInputStream.read(buffer, 0, bufferSize);
        while (bytesRead > 0) {
            dos.write(buffer, 0, bufferSize);
            bytesAvailable = fileInputStream.available();
            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            bytesRead = fileInputStream.read(buffer, 0, bufferSize);
        }
        // send multipart form data necesssary after file data...
        dos.writeBytes(lineEnd);
        dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
        // close streams
        Log.e("Debug", "File is written");
        fileInputStream.close();
        dos.flush();
        dos.close();
    } catch (MalformedURLException ex) {
        Log.e("Debug", "error: " + ex.getMessage(), ex);
    } catch (IOException ioe) {
        Log.e("Debug", "error: " + ioe.getMessage(), ioe);
    }
    // ------------------ read the SERVER RESPONSE
    try {
        inStream = new DataInputStream(conn.getInputStream());
        String str;

        while ((str = inStream.readLine()) != null) {
            Log.e("Debug", "Server Response " + str);
        }
        inStream.close();

    } catch (IOException ioex) {
        Log.e("Debug", "error: " + ioex.getMessage(), ioex);
    }

}

**編輯:為了更加清楚一點,我希望它可以在我的PHP腳本中訪問$ _REQUEST ['path'](可能='/ documents /'之類)之類的值以及$ _FILES ['uploadedfile']的實際文件

String urlToSendRequest = "https://example.net";
String targetDomain = "example.net";

DefaultHttpClient httpClient = new DefaultHttpClient();
HttpHost targetHost = new HttpHost(targetDomain, 80, "http");

HttpPost httpPost = new HttpPost(urlToSendRequest);
// Make sure the server knows what kind of a response we will accept
// httpPost.addHeader("Accept", "text/xml");
// Also be sure to tell the server what kind of content we are sending
httpPost.addHeader("Content-Type", "application/xml"); 

StringEntity entity = new StringEntity("<input>test</input>", "UTF-8");
entity.setContentType("application/xml");
httpPost.setEntity(entity);

 HttpResponse response = httpClient.execute(httpPost, context);

 Reader r = new InputStreamReader(response.getEntity().getContent());

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM