Java 上傳檔案到 Restful API

摘要:Java 上傳檔案

這個方法是從網路上學來的

包裝成自己使用的方法

大部分好像是用來寫在Android手機上,Android手機使用RestApi上傳檔案時需要用到。(上傳照片之類的)

 

我將一般欄位的key,value及檔案欄位的key,value分開,分別使用data_map及file_map儲存(類別HashMap<String,String>)

file_map則是control_name ,file_path 為key,value型式。

data_map則是control_name,control_value為key,value型式。

 

我使用的是HttpsURLConnection 做connection 連線上傳。

Content-Type需設為"multipart/form-data; boundary = " + BOUNDARY

BOUNDARY是自定,這裡定的是 "=================================="

用來分辨不同的control資料,一個區段為一個control 資料

每個區段開始以HYPHENS + BOUNDARY來分辨

HYPHENS= "--";

如果我傳輸兩個control資訊到api的話(control_name,control_name2),file control 為file_control 

則傳輸資料如下

--==================================

Content-isposition: form-data; name=control_name

 

control_value

--==================================

 

Content-isposition: form-data; name=control_name2

 

control_value2

--==================================

Content-isposition: form-data; name=file_control;filename=D:\file.txt

Content-Type: text/plain

 

file_content

 

以下是Java Code Funtion ,並回傳Response

    public String post_file(String rest_api_url,HashMap data_map,HashMap file_map) throws Exception
    {
        String result = "";
        try
        {
            final String BOUNDARY   = "==================================";
            final String HYPHENS    = "--";
            final String CRLF       = "\r\n";
            URL url = new URL(rest_api_url);
            HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);

            conn.setRequestProperty("Content-Type","multipart/form-data; boundary="+BOUNDARY);

            DataOutputStream dataOS = new DataOutputStream(conn.getOutputStream());
            //傳資料
            for(String key:data_map.keySet())
            {
                // 寫--==================================
                dataOS.writeBytes(HYPHENS+BOUNDARY+CRLF);
                dataOS.writeBytes("Content-Disposition: form-data; name= \""+key+"\""+CRLF);
                dataOS.writeBytes(CRLF);
                dataOS.writeBytes(data_map.get(key)+CRLF);
            }
            //傳檔案===============================================================================
            for(String key:file_map.keySet())
            {
                FileInputStream fileInputStream = new FileInputStream(new File(file_map.get(key)));
                 // 寫--==================================
                dataOS.writeBytes(HYPHENS+BOUNDARY+CRLF);
                dataOS.writeBytes("Content-Disposition: form-data; name=\""+key+"\"; filename=\""+file_map.get(key)+"\""+CRLF);  // 寫(Disposition)
                dataOS.writeBytes("Content-Type: text/plain"+CRLF);         // 寫(Content Type)
                dataOS.writeBytes(CRLF);

                int iBytesAvailable = fileInputStream.available();
                byte[] byteData = new byte[iBytesAvailable];
                int iBytesRead = fileInputStream.read(byteData, 0, iBytesAvailable);
                while (iBytesRead > 0) {
                    dataOS.write(byteData, 0, iBytesAvailable); // 開始寫內容
                    iBytesAvailable = fileInputStream.available();
                    iBytesRead = fileInputStream.read(byteData, 0, iBytesAvailable);
                }
                dataOS.writeBytes(CRLF);
                fileInputStream.close();
            }
             // (結束)寫--==================================--
            dataOS.writeBytes(HYPHENS+BOUNDARY+HYPHENS);
            dataOS.flush();
            dataOS.close();

            //取得回應
            // 定義BufferedReader輸入流來讀取URL的響應
            BufferedReader reader =  new  BufferedReader( new  InputStreamReader(conn.getInputStream()));
            String line =  null ;
            StringBuilder sb = new StringBuilder();
            while  ((line = reader.readLine()) !=  null ) {
                sb.append(line);
            }

            if (conn != null) {
                conn.disconnect();
            }
            conn =null;
            result = sb.toString();
            sb.setLength(1);
            sb = null;
        }catch (Exception ex)
        {
            ex.printStackTrace();
        }

        return result;
    }