`
wildwind
  • 浏览: 99837 次
  • 性别: Icon_minigender_1
  • 来自: 苏州
社区版块
存档分类
最新评论

如何通过网络上传文件?

阅读更多
How do I upload a file to my servlet or JSP?
On the client side, the client's browser must support form-based upload. Most modern browsers do, but there's no guarantee. For example,
<FORM ENCTYPE='multipart/form-data'
method='POST' action='/myservlet'>
<INPUT TYPE='file' NAME='mptest'>
<INPUT TYPE='submit' VALUE='upload'>
</FORM>
The input type &amp;quot;file&amp;quot; brings up a button for a file select box on the browser together with a text field that takes the file name once selected. The servlet can use the GET method parameters to decide what to do with the upload while the POST body of the request contains the file data to parse.

When the user clicks the "Upload" button, the client browser locates the local file and sends it using HTTP POST, encoded using the MIME-type multipart/form-data. When it reaches your servlet, your servlet must process the POST data in order to extract the encoded file. You can learn all about this format in RFC 1867.

Unfortunately, there is no method in the Servlet API to do this. Fortunately, there are a number of libraries available that do. Some of these assume that you will be writing the file to disk; others return the data as an InputStream.

Once you process the form-data stream into the uploaded file, you can then either write it to disk, write it to a database, or process it as an InputStream, depending on your needs. See How can I access or create a file or folder in the current directory from inside a servlet? and other questions in the Servlets:Files Topic for information on writing files from a Servlet.

Please note that you can't access a file on the client system directly from a servlet; that would be a huge security hole. You have to ask the user for permission, and currently form-based upload is the only way to do that.

[This FAQ based on earlier posts by Thomas Moore, Detlef Pleiss (dpleiss@os-net.de), and others.]

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics