java - 如何在 Android 中通过 http 协议(protocol)将多个文件和文本同时发送到服务器?

标签 java php android file-upload multipartform-data

我想向服务器发送一个文件和一些变量,以使用 AsyncTask 将其插入到 Android 应用程序的表格中。这是我的 Java 代码:

try {

    URL url = new URL(upLoadServerUri);
    HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
    httpURLConnection.setRequestMethod("POST");
    httpURLConnection.setDoOutput(true);
    httpURLConnection.setDoInput(true);
    httpURLConnection.setUseCaches(false);
    OutputStream  outputStream = httpURLConnection.getOutputStream();
    BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream,"UTF-8"));
    String post_data= URLEncoder.encode("username" , "UTF-8")+"="+URLEncoder.encode(username,"UTF-8");
    bufferedWriter.write(post_data);
    bufferedWriter.flush();
    bufferedWriter.close();
    outputStream.close();
    InputStream inputStream = httpURLConnection.getInputStream();
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"));
    result="";
    String line="";
    while ((line=bufferedReader.readLine()) != null){
        result += line;

    }
    bufferedReader.close();
    inputStream.close();
    httpURLConnection.disconnect();


}catch (MalformedURLException e){
    e.printStackTrace();
}catch (IOException e){
    e.printStackTrace();
}
try {

    FileInputStream fileInputStream = new FileInputStream(sourceFile);
    URL url = new URL(upLoadServerUri);

    // 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("bill", sourceFileUri);

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

    dos.writeBytes(twoHyphens + boundary + lineEnd);
    dos.writeBytes("Content-Disposition: form-data; name=\"bill\";filename=\""
            + sourceFileUri + "\"" + 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)
    serverResponseCode = conn.getResponseCode();
    String serverResponseMessage = conn
            .getResponseMessage();

    // close the streams //
    fileInputStream.close();
    dos.flush();
    dos.close();
    return result;


} catch (MalformedURLException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}

和PHP代码:

if (is_uploaded_file($_FILES['bill']['tmp_name'])) {
   $uploads_dir = './sensorLog/$user_name';
   $tmp_name = $_FILES['bill']['tmp_name'];
   $pic_name = $_FILES['bill']['name'];
   move_uploaded_file($tmp_name, $uploads_dir.$pic_name);

   if($conn->query($mysql_qry) === TRUE) {
      echo "upload and update successful";
         }else { echo "Error" . $mysql_qry . "<br>" . $conn->error;}

   }else{ echo "File not uploaded successfully.";  }

我使用了两个 httpconnection 对象,我认为这是问题所在。如何同时发送变量和文件?此代码将文件上传到服务器,但表未更新。它只是添加一个空行:(。

最佳答案

使用此类发送多部分请求:

class MultipartUtility {
    public HttpURLConnection httpConn;
    public OutputStream request;//if you wanna send anything out of ordinary use this;
    private final String boundary =  "*****";//alter this as you wish
    private final String crlf = "\r\n";
    private final String twoHyphens = "--";
    public MultipartUtility(String requestURL)
            throws IOException {
        URL url = new URL(requestURL);
        httpConn = (HttpURLConnection) url.openConnection();
        httpConn.setUseCaches(false);
        httpConn.setDoOutput(true);
        httpConn.setDoInput(true);
        httpConn.setRequestMethod("POST");
        //alter this part if you wanna set any headers or something
        httpConn.setRequestProperty("Connection", "Keep-Alive");
        httpConn.setRequestProperty("Cache-Control", "no-cache");
        httpConn.setRequestProperty(
                "Content-Type", "multipart/form-data;boundary=" + this.boundary);
        request = httpConn.getOutputStream();
    }
    //or add some other constructor to better fit your needs; like set cookies and stuff
    public void addFormField(String name, String value)throws IOException {
        request.write(( this.twoHyphens + this.boundary + this.crlf).getBytes());
        request.write(("Content-Disposition: form-data; name=\"" + name + "\""+ this.crlf).getBytes());
        request.write(this.crlf.getBytes());
        request.write((value).getBytes());
        request.write(this.crlf.getBytes());
        request.flush();
    }
    public void addFilePart(String fieldName, File uploadFile)
            throws IOException,Exception {
        if(uploadFile.isDirectory())throw new Exception("for real? what do you expect to happen?");
        request.write((this.twoHyphens + this.boundary + this.crlf).getBytes());
        request.write(("Content-Disposition: form-data; name=\"" +
                fieldName + "\";filename=\"" +
                uploadFile.getName()+ "\"" + this.crlf).getBytes());
        request.write(this.crlf.getBytes());
        InputStream is=new FileInputStream(uploadFile);
        byte[] bytes = new byte[1024];
        int c=is.read(bytes);
        while(c>0){
            request.write(bytes,0,c);
            c=is.read(bytes);
        }
        request.write(this.crlf.getBytes());
        request.flush();
        is.close();
    }
    public String finish() throws IOException {
        String response ="";
        request.write((this.twoHyphens + this.boundary +
                this.twoHyphens + this.crlf).getBytes());
        request.flush();
        request.close();
        int status = httpConn.getResponseCode();
        if (status == HttpURLConnection.HTTP_OK) {
            InputStream responseStream = httpConn.getInputStream();
            byte[] b=new byte[1024];
            int c=responseStream.read(b);
            while(c>0){
                response=response+new String(b,0,c);
                c=responseStream.read(b);
            }
            responseStream.close();
        } else {
            httpConn.disconnect();
            throw new IOException("Server returned non-OK status: " + status);
        }
        httpConn.disconnect();
        return response;
    }
    public InputStream finish_with_inputstream()throws Exception{
        request.write((this.twoHyphens + this.boundary +
                this.twoHyphens + this.crlf).getBytes());
        request.flush();
        request.close();
        int status = httpConn.getResponseCode();
        if (status == HttpURLConnection.HTTP_OK) {
            return httpConn.getInputStream();
        } else {
            throw new IOException("Server returned non-OK status: " + status);
        }
    }
}

例子:

    try{
        MultipartUtility m=new MultipartUtility("https://mydomain");//now add you different data parts;
        m.addFilePart("file_part",new File("some_file_location"));
        m.addFormField("value_name","value");
        //call either of the below methods based on what you need; do not call both!
        String result=m.finish();//call this if the response is a small text 
        InputStream is=m.finish_with_inputstream(); //call this if the response is huge and not fitting in memory; don't forget to disconnect the connection afterwards;
    } catch (IOException e) {
        e.printStackTrace();
    }

现在您可以在 php 端的一个请求中处理所有这些数据:

$value=$_POST["value_name"];
$file_data=file_get_contents($_FILES["file_part"]["tmp_name"])

所以对于你的情况,它会像下面这样:

try{
        MultipartUtility m=new MultipartUtility("https://mydomain");
        m.addFilePart("bill",new File(sourceFile));
        m.addFormField(URLEncoder.encode("username" , "UTF-8"),URLEncoder.encode(username,"UTF-8"));
        String result=m.finish();
    } catch (Exception e) {
        e.printStackTrace();
    }

关于java - 如何在 Android 中通过 http 协议(protocol)将多个文件和文本同时发送到服务器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54731371/

相关文章:

java 模块化划分健全性检查

PHP 正则表达式 : Replace substring between two special character

php - MySQL 所选行的大小

php - C9 - 如何获取查询结果以及如何从查询中获取行数?

具有不同半径值的布局中的Android圆角

java - 如何从 Java3D 中的 IndexedGeometryArray 读取顶点坐标和三角形索引?

java - 如何隐藏 JPanel 并在其他 Java 文件中打开另一个 JPanel?

java - 用 Java 实现多个接口(interface) - 有没有办法委托(delegate)?

android - anko logging方法无法解决

java - 无法重新安装崩溃的 Sony SmartWatch Control