使用smartupload.jar实现文件上传下载
使用smartupload.jar实现文件上传下载
准备上传的页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head><title>文件上传下载</title>
</head>
<body>
<form action="/uploadtest" method="post" enctype="multipart/form-data">图片:<input type="file" name="pic"><input type="submit" value="上传">
</form>
</body>
</html>
注:(1)form标签中要添加enctype属性
(2)提交方式必须是post
开始获取数据,保存文件
@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {//1.创建上传文件的对象SmartUpload smartUpload = new SmartUpload();//2.初始化上传操作PageContext pageContext = JspFactory.getDefaultFactory().getPageContext(this, req, resp, null, false, 1024, true);smartUpload.initialize(pageContext);//2.1 设置编码smartUpload.setCharset("utf-8");//3.上传try {smartUpload.upload();} catch (SmartUploadException e) {e.printStackTrace();}//4.获取文件信息File file = smartUpload.getFiles().getFile(0);String fileName = file.getFileName();String contentType = file.getContentType();//5.指定上传的路径String uploadPath = "/uploadfiles/"+fileName;//6.保存到指定位置try {file.saveAs(uploadPath,File.SAVEAS_VIRTUAL);} catch (SmartUploadException e) {e.printStackTrace();}//7.跳转到指定页面req.setAttribute("fileName",fileName);req.getRequestDispatcher("show.jsp").forward(req,resp);}
注:
(1)此时如果表单中有其他数据时,不能通过request直接获取,需要通过SmartUpload对象获取 String name=su.getRequest().getParameter(“bookName”);并且该代码要在SmartUpload操作完成后添加
(2)解决乱码:
new String(name.getBytes(“GBK”),“utf-8”)
注:斜杠方向:/
注意:
smartupload常用方法
文件下载
@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {String filename = req.getParameter("filename");String path = "/uploadfiles/"+filename;//设置响应头信息和响应类型resp.setContentType("application/octet-stream");resp.addHeader("Content-Disposition","attachment;filename="+filename);//跳转页面req.getRequestDispatcher(path).forward(req,resp);//清空缓存区resp.flushBuffer();}
效果如下:
上传之后跳到show页面
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head><title>文件上传展示页面</title>
</head>
<body>
<a href="${pageContext.request.contextPath}/download?filename=${fileName}">下载</a>
<img src="uploadfiles/${fileName}"/>
</body>
</html>
点击下载之后,存入对应文件夹