在J2EE开发中,使用浏览器上传文件很简单,服务器用Apache的Commons FileUpload实现就可以了。但是在开发C/S架构的程序时就需要自己处理。用代码实现文件上传需要对表单的multipart/form-data有所了解,(表单默认情况下使用application/x-www-form-urlencoded)。
在multipart/form-data中Content-Type是这样的:
boundary是表示分隔,用于分隔多个文件。格式是 — 后面可以跟随一串随机数。
我自己写了一个Servlet,使用jsp表单提交,打印出request中的流,用于分析格式。
后台打印:
分析:
------WebKitFormBoundaryxHKqg3ljAsuAFWBO Content-Disposition: form-data; name="upfile"; filename="test.png" Content-Type: image/png (二进制内容省略...) ------WebKitFormBoundaryxHKqg3ljAsuAFWBO
其中Content-Type是文件类型,这个是浏览器自己判断的。
------WebKitFormBoundaryxHKqg3ljAsuAFWBO Content-Disposition: form-data; name="note" 字段内容 ------WebKitFormBoundaryxHKqg3ljAsuAFWBO
所有文件或字段的分隔用
------WebKitFormBoundaryxHKqg3ljAsuAFWBO
当执行到未尾,最后一个分隔要加上–
------WebKitFormBoundaryxHKqg3ljAsuAFWBO--
当时自己实现时忽略掉这个–,导致代码一直报错:
org.apache.commons.fileupload.FileUploadException: Processing of multipart/form-data request failed. Stream ended unexpectedly
分析完multipart/form-data的格式后,自己写代码就比较容易了。
客户端发送:
服务端接收:
该工具类可以用于JAVA或Android,源码下载:uploadfile source