→ chrisho: readxxxx 有很多方法何苦只用 readLine()... 07/31 12:27
我參考這網站http://ccc.kmit.edu.tw/code/WebServer/WebServer.htm
用Server socket實做了一個Web service
讓使用者用表單傳檔案到Server端,不過檔案卻無法使用,
似乎是表單在用post方法傳時的結尾訊息也被加進去了,
如果是txt或htm類型的檔案還可以找出結尾的格式加以去除,
但mp3或是ppt這種就沒辦法了,想問一下要如何過濾post的訊息?
post 是包成開頭(含本機位置、類型等資訊) 空白行結尾
檔案本體
結尾訊息?(這一部分用txt測試可以看到,但非文字檔類型幾乎都是亂碼)
表單部分就只是單純的一個含傳檔案按鈕的html
我的傳法
//以下是處理post的部分
//讀標頭
while (true) {
String line = in.readLine();
if (line == null) break;
request += line+"\r\n";
if (line.length() == 0) break;
}
// 讀取到第一個空白行為止,這是post一開始的訊息。包含檔名等資訊
while (true) {
String line = in.readLine();
if (line == null) break;
request += line+"\r\n";
if (line.length() == 0) break;
}
// 根據 Content-Length: ,讀取到第一個空白行後面的 POST 表單訊息。
//也就是取得post訊息的長度,似乎不只有檔案大小的長度
String lengthStr = innerText(request.toLowerCase(),
"content-length:",
"\r\n");
//讀取表單傳進來的資料並寫入檔案
//但會一起把結尾訊息寫入
if (lengthStr != null) {
int contentLength = Integer.parseInt(lengthStr.trim());
byte[] bytes = new byte[contentLength];
in.read(bytes);
//寫入檔案
FileOutputStream fos;
//root是設為程式所在位置,包含完整路徑
fos = new FileOutputStream(new File(root+"//tmp"));
fos.write(bytes);
fos.flush();
fos.close();
}
}
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 140.114.224.11
※ 編輯: ptthuey 來自: 140.114.224.11 (07/31 00:27)
※ 編輯: ptthuey 來自: 140.114.224.11 (07/31 00:27)
※ 編輯: ptthuey 來自: 140.114.224.11 (07/31 00:34)