使用JSPmartUpload实现文件的上传和下载

来源:互联网 发布:剑网3军娘捏脸数据成女 编辑:程序博客网 时间:2024/06/05 20:52

文件上传

public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {response.setContentType("text/html;charset=UTF-8");PrintWriter out = response.getWriter();request.setCharacterEncoding("UTF-8");response.setCharacterEncoding("UTF-8");try {/*以上两行不能颠倒,否则会出现乱码*/SmartUpload su = new SmartUpload();// 设置允许上传的文件su.setAllowedFilesList("txt,jpg");// 获取config对象ServletConfig config = this.getServletConfig();// 上传初始化su.initialize(config, request, response);// 上传文件su.upload();// 读取网站当前实际物理路径String rootPath = config.getServletContext().getRealPath("/");// 打印获取的当前路径System.out.println(rootPath);String uname = su.getRequest().getParameter("uname");// 根据用户名创建一个目录专门保存用户图片File file = new File(rootPath+uname);if (!file.exists()) {file.mkdir();}// 将上传文件全部保存到指定目录int  count = su.save(file.getAbsolutePath());System.out.println("打印count"+count);out.print("保持成功");} catch (Exception e) {out.print("保存失败");e.printStackTrace();}out.close();}

文件下载

public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {response.setContentType("text/html;charset=UTF-8");request.setCharacterEncoding("UTF-8");response.setCharacterEncoding("UTF-8");SmartUpload su = new SmartUpload();su.initialize(this.getServletConfig(), request, response);su.setContentDisposition(null);String rootPath = this.getServletConfig().getServletContext().getRealPath("/");try {su.downloadFile(rootPath+"/ming.txt");} catch (SmartUploadException e) {e.printStackTrace();}}