【ZT】Jsp/Servlet:实现文件上传与下载【一】

12 篇文章 0 订阅
1.客户端上传文件
客户端通过一个Jsp页面,上传文件到服务器,该Jsp页面必须含有File类表单,并且表单必须设置enctype="multipart/form-data"。提交表单时通过内置对象requestrequest.getInputStream();方法获得一个输入流。
在上传文件时,会有附加信息,如下所示:
-----------------------------7d71042a40328
Content-Disposition: form-data; name="fileforload"; filename="C:\Documents and Settings\ZJ\桌面\book.txt"
Content-Type: text/plain
//此处为文件内容
-----------------------------7d71042a40328
Content-Disposition: form-data; name="submit"
 
commit
-----------------------------7d71042a40328--
附加信息大小为297字节(不确定这个值,测试得到),可通过request.getContentLength()>297来判断是否上传了文件还是提交空字符串。
2.测试
fileupload.jsp负责提交文件,accept.jsp负责实现上传功能。
fileupload.jsp
<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=GB18030">
  <title>This page for FileUpload</title>
</head>
<body>
  <p>Choose the file for uploading:
  <form action="accept.jsp" method=post enctype="multipart/form-data">
    <input type=file name=fileforload size=30>
    <br>
    <input type=submit value=commit name=submit>
  </form>
</body>
</html>
 
accept.jsp
<html>
<head>
<%@ page language="java" import="java.io.*" %>
<meta http-equiv="Content-Type" content="text/html; charset=GB18030">
<title>This page for response</title>
</head>
<body>
    <%
    try {
       if (request.getContentLength() > 297) {
           InputStream in = request.getInputStream();
           File f = new File("d:/temp""test.txt");
           FileOutputStream o = new FileOutputStream(f);
           byte b[] = new byte[1024];
           int n;
           while ((n = in.read(b)) != -1) {
               o.write(b, 0, n);
           }
           o.close();
           in.close();
           out.print("File upload success!");
           else {
              out.print("No file!");
           }
       catch (IOException e) {
           out.print("upload error.");
           e.printStackTrace();
       }
    %>
    </body>
</html>
 
服务器端得到的上传文件I like.txt,取名为test.txt
-----------------------------7d75b1540328
Content-Disposition: form-data; name="fileforload"; filename="C:\Documents and Settings\ZJ\桌面\I like.txt"
Content-Type: text/plain
 
我喜欢驾驭着代码在风驰电掣中创造完美;
我喜欢操纵着代码在随心所欲中体验生活;
我喜欢用心情代码编制我小小的与众不同;
每一段新的代码在我手中延生对我来说就象观看刹那花开的感动;
我不需要焦点.因为我就是焦点!
 
-----------------------------7d75b1540328
Content-Disposition: form-data; name="submit"
 
commit
-----------------------------7d75b1540328--
3.去除附加信息
按照HTTP协议,文件表单提交的信息中,前4行和后5行是表单本身的信息,中间部分才是上传的文件的内容。下例对上传的文件进行处理,获取文件名,并去除附加信息。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值