【问题标题】:Post image to server by android and get response that by PHP code通过 android 将图像发布到服务器并通过 PHP 代码获取响应
【发布时间】:2015-12-03 10:00:32
【问题描述】:

我正在使用 HTTPUrlConnection 将图像发送到服务器。如何编写 php 代码来接收图像并在没有 json 的情况下发送响应。您能否解释一下 php 将如何接收没有 json 结构的文件数据。

 public void uploadFile(String sourceFileUri, String upLoadServerUri) {
    URL url=null;
    HttpURLConnection connection = null;

    Bitmap bm = BitmapFactory.decodeFile(sourceFileUri);
    ByteArrayOutputStream bao = new ByteArrayOutputStream();
    bm.compress(Bitmap.CompressFormat.JPEG, 10, bao);

    try {
            //Create connection
            url = new URL(upLoadServerUri);
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            connection.setRequestProperty("Content-Language", "en-US");

            connection.setUseCaches(false);
            connection.setDoInput(true);
            connection.setDoOutput(true);

            //Send request
            DataOutputStream writer = new DataOutputStream(connection.getOutputStream());

            writer.writeBytes(bao.toString());
            writer.flush();
            writer.close();

            //Get Response
            InputStream is = connection.getInputStream();
            BufferedReader rd = new BufferedReader(new InputStreamReader(is));
            String line;
            StringBuffer response = new StringBuffer();
            while ((line = rd.readLine()) != null) {
                response.append(line);
                response.append('\r');
            }
            rd.close();


        } catch (Exception e) {

            e.printStackTrace();
            return null;

        } finally {

            if (connection != null) {
                connection.disconnect();
            }
        }
}

【问题讨论】:

    标签: php android http-post httpurlconnection


    【解决方案1】:

    这是我正在运行的代码。 //安卓

    String sourceFileUri = Environment.getExternalStorageDirectory()+"filename.jpeg";
    
                String fileName = sourceFileUri;
    
                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;
                File sourceFile = new File(sourceFileUri);
    
                if (!sourceFile.isFile()) {
    
                    return null;
    
                }
    
                String fullpath = "";
    
                fullpath = sourceFile + "";
                Log.e("fullpath", fullpath);
                try {
                    // open a URL connection to the Servlet
                    FileInputStream fileInputStream = new FileInputStream(sourceFileUri);
                    Log.e("fileinputstream", "" + fileInputStream);
                    URL url = new URL("abc.com/upload.php");
                    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
                            .permitAll().build();
                    StrictMode.setThreadPolicy(policy);
                    // Open a HTTP connection to the URL
                    conn = (HttpURLConnection) url.openConnection();
                    // int lenghtOfFile = conn.getContentLength();
                    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", fileName);
    
                    dos = new DataOutputStream(conn.getOutputStream());
    
                    dos.writeBytes(twoHyphens + boundary + lineEnd);
                    dos.writeBytes("Content-Disposition: form-data; name=\"bill\";filename=\""
                            + fileName + "\"" + lineEnd);
    
                    dos.writeBytes(lineEnd);
    
                    // create a buffer of maximum size
                    bytesAvailable = fileInputStream.available();
                    Log.e("" + bytesAvailable, "BytesAvailable");
                    bufferSize = Math.min(bytesAvailable, maxBufferSize);
                    buffer = new byte[bufferSize];
                    Log.e("" + buffer, "Buffer");
                    // read file and write it into form...
                    bytesRead = fileInputStream.read(buffer, 0, bufferSize);
                    // long total = 0;
                    Log.e("" + bytesRead, "BytesRead");
                    while (bytesRead > 0) {
                        // total += count;
                        // publishProgress("" + (int) ((total * 100) /
                        // lenghtOfFile));
    
                        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)
    
               String serverResponseMessage = conn.getResponseMessage();  
                    Log.e("Server Response code", "" + serverResponseCode);
                    if (serverResponseMessage == "sucess") {
    
    
                         System.out.println("file uploaded");
                    }
    
                    // close the streams //
                    fileInputStream.close();
                    dos.flush();
                    dos.close();
    
                } catch (Exception e) {
                    Log.d("error", e.getMessage());
                }
    

    //php

    <?php
        if (is_uploaded_file($_FILES['bill']['tmp_name'])) {
         $name="filename";   
    
         $tmp_name = $_FILES['bill']['tmp_name'];
         $pic_name = $_FILES['bill']['name'];
         $ext = explode('.',$pic_name);
         $extension = $ext[1];
           if($extension=='png'){
               unlink( $name.'.jpg'); 
                }
    
          if($extension=='jpg'){
               unlink( $name.'.png'); 
                 }
    
          move_uploaded_file($tmp_name,  $name.'.'.$extension );
                echo "sucess";
                }
            else{
             echo "File not uploaded successfully.";
                }        
         ?>
    

    【讨论】:

    • 感谢 raj,我在很多地方都看到了同样的情况,但你能解释一下为什么我们使用 String twoHyphens = "--";字符串边界 = "*****";是否有必要。如何使用 "Content-Disposition: form-data; name=\"bill\";filename=\" 从 PHP 代码中获取数据
    • 看下 android 代码有 serverResponseMessage 你从 php 得到响应。这将使您在文件上传和文件上传失败时成功。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-04
    • 2015-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-16
    相关资源
    最近更新 更多