【问题标题】:How to send post data along with a file in Android?如何在 Android 中将发布数据与文件一起发送?
【发布时间】:2015-02-13 09:38:48
【问题描述】:

过去几天我一直在尝试在 Android 中发布多部分表单,但无法完全发送字符串数据和文件。我正在使用以下代码上传我的文件,它工作得很好。但是在向我的请求中添加字符串数据时,它就不足了。

假设我需要将profile_id=1234&text=HERE IS MY TEXT&global=0 附加到请求中。我该怎么做?

String fileName = photoPath;

HttpURLConnection conn = null;
DataOutputStream dos = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
try {

    // open a URL connection to the Servlet
    FileInputStream fileInputStream = new FileInputStream(new File(photoPath));
    URL url = new URL(Util.URL_POST_FEED);

    // Open a HTTP  connection to  the URL
    conn = (HttpURLConnection) url.openConnection();
    conn.setDoInput(true); // Allow Inputs
    conn.setDoOutput(true); // Allow Outputs
    conn.setUseCaches(false); // Don't use a Cached Copy
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Connection", "Keep-Alive");
    conn.setRequestProperty("ENCTYPE", "multipart/form-data");
    conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
    conn.setRequestProperty("file", fileName);


    dos = new DataOutputStream(conn.getOutputStream());

    dos.writeBytes(twoHyphens + boundary + lineEnd);
    dos.writeBytes("Content-Disposition: form-data; name=\"file\";filename=\""
            + fileName + "\"" + 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);

    // Responses from the server (code and message)
    int serverResponseCode = conn.getResponseCode();
    String serverResponseMessage = conn.getResponseMessage();


    Log.i("uploadFile", "HTTP Response is : "
            + serverResponseMessage + ": " + serverResponseCode);

    if (serverResponseCode == 200) {

        runOnUiThread(new Runnable() {
            public void run() {


                Toast.makeText(c, "File Upload Complete.",
                        Toast.LENGTH_SHORT).show();
            }
        });
    }
    InputStream stream = conn.getInputStream();
    InputStreamReader isReader = new InputStreamReader(stream);

    //put output stream into a string
    BufferedReader br = new BufferedReader(isReader);
    Log.d("Read", br.readLine());
    //close the streams //
    fileInputStream.close();
    dos.flush();
    dos.close();

} catch (MalformedURLException ex) {

    ex.printStackTrace();

    runOnUiThread(new Runnable() {
        public void run() {
            Toast.makeText(c, "MalformedURLException",
                    Toast.LENGTH_SHORT).show();
        }
    });

    Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
} catch (Exception e) {

    e.printStackTrace();

    runOnUiThread(new Runnable() {
        public void run() {
            Toast.makeText(c, "Got Exception : see logcat ",
                    Toast.LENGTH_SHORT).show();
        }
    });
    Log.e("Upload file to server Exception", "Exception : "
            + e.getMessage(), e);
}

【问题讨论】:

标签: android forms post file-upload


【解决方案1】:

检查this tutorial。希望它会有所帮助。

它使用自定义的MultipartUtility 类手动创建要通过连接发送的请求正文。

【讨论】:

    猜你喜欢
    • 2017-12-20
    • 1970-01-01
    • 2017-04-08
    • 1970-01-01
    • 2015-10-01
    • 2020-08-14
    • 2020-05-16
    • 2014-01-22
    • 2016-08-12
    相关资源
    最近更新 更多