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

文件上传

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();
		}
	}




  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值