作者ptthuey (天秤守望者)
看板java
标题[问题] 关於用表单的POST传资料
时间Thu Jul 31 00:23:58 2008
我参考这网站
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)
1F:→ chrisho: readxxxx 有很多方法何苦只用 readLine()... 07/31 12:27