学习笔记:文件的上传和下载

<form action="upload" method="post" enctype="multipart/form-data">

enctype="multipart/form-data"        //不对字符进行编码

准备上传的页面: 

<form action="toUpload" method="post" enctype="multipart/form-data" >
     书名:<input type="text" name="bookName"/><br>
     图片:<input type="file" name="自定义名称"/><br>
     <input type="submit" value="提交"/>
 </form>

服务器端获取数据并保存文件:

public void upload(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
     try {
        //上传文件
         SmartUpload su=new SmartUpload();
         //获得pageContext对象
         JspFactory factory=JspFactory.getDefaultFactory();
         PageContext pagecontext= factory. getPageContext(this, request,response,             null,false,1024,true);
         su.initialize(pagecontext);
         su.setCharset("utf-8");
         //实现文件数据的上传
         su.upload();
         File file = su.getFiles().getFile(0);
         //得到文件的基本信息
         String filename=file.getFileName();
         String type=file.getContentType();
         System.out.println("type="+type);
         String url="uploadfile/"+filename;
         //将上传文件保存到指定目录
         file.saveAs(url, SmartUpload.SAVE_VIRTUAL);
         request.setAttribute("filename",filename);
         String uname=su.getRequest().getParameter("uname");
         system.out.println("uname="+uname);
         request.getRequestDispatcher("success.jsp").forward(request, response);
    } catch (SmartUploadException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
    }
 }
注: (1) 此时如果表单中有其他数据时,不能通过 request 直接获取,需要通过 SmartUpload对象获取
 String name=su.getRequest().getParameter("bookName");
并且该代码要在SmartUpload操作完成后添加

解决乱码: 

 new String(name.getBytes("GBK"),"utf-8")

 

 smartupload常用方法

 

文件下载 

 String name=request.getParameter("filename");
 String url="uploadfile/"+name; 

//将响应的内容设置为通用的二进制流
 response.setContentType("application/octet-stream");

 //attachment 告诉浏览器以附件的方式下载文件(弹出下载框)
 name=URLEncoder.encode(name,"utf-8");
 response.addHeader("Content-Disposition","attachment;filename="+name); 
 
 request.getRequestDispatcher(url).forward(request, response);
 //清空缓冲区:将服务端缓冲区的文件内容,立即权并不传送给客户端
 response.flushBuffer();

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值