文件的上传和下载

文件的上传


		private String makeFileName (String filename) {
		         //为防止文件覆盖的现象发生,要为上传文件产生一个唯一的文件名
		         return UUID.randomUUID().toString() + "_" + filename;
		     }

//定义文件保存路径
	String savePath = "/home/sxd/Downloads/wenjan";
//this.getServletContext().getRealPath("/WEB-INF/upload");
	File file = new File(savePath);
	//判断上传文件的保存目录是否存在 不存在就创建
	if (!file.exists() && !file.isDirectory()) {
	    file.mkdir();
	 }
	//消息提示
	String message = "";
	try{
	    DiskFileItemFactory factory = new DiskFileItemFactory();
	    ServletFileUpload upload = new ServletFileUpload(factory);
	    upload.setHeaderEncoding("UTF-8"); 
	    List<FileItem> list = upload.parseRequest(request);
	    for(FileItem item : list){
	        if(!item.isFormField()){
	            String filename = item.getName();
	            System.out.println(filename);
	            if(filename==null || filename.trim().equals("")){
	                continue;
	            }
	            filename = filename.substring(filename.lastIndexOf("\\")+1);
	            String saveFilename = makeFileName(filename);
	            InputStream in = item.getInputStream();
	            FileOutputStream fout = new FileOutputStream(savePath + System.getProperty("file.separator") + saveFilename);
	            byte buffer[] = new byte[1024];
	            int len = 0;
	            while((len=in.read(buffer))>0){
	                fout.write(buffer, 0, len);
	            }
	            in.close();
	            fout.close();
	            //删除处理文件上传时生成的临时文件
	            item.delete();
	            message = "文件上传成功!";
	        }
	     }
	}catch (Exception e) {
		message= "文件上传失败!";
		e.printStackTrace();
	}
	request.setAttribute("message",message);
	request.getRequestDispatcher("/message.jsp").forward(request, response);
前端页面

	<form action="Upload.jsp" method="post" enctype="multipart/form-data">
		<span>选择文件:</span><input type="file" name="upload">
		<div>
			<input type="submit" value="上传文件">
		</div>
	</form>

文件是上传需要的jar


 文件的下载


response.setContentType("application/x-download");
 String basePath = request.getSession().getServletContext().getRealPath("");  

String fileDownloadName = "/home/sxd/Downloads/peizi.txt";
//"C:\\Users\\Administrator\\Desktop\\files\\test.txt"; // 下载的文件的物理路径+文件名
String fileDisplayName = "text.txt";// 给用户提供的下载文件名
fileDisplayName = URLEncoder.encode

(fileDisplayName, "UTF-8");
response.addHeader("Content-Disposition", 

"attachment;filename=" + fileDisplayName);
OutputStream outp = null;
FileInputStream in = null;
try {
    outp = response.getOutputStream();
    in = new FileInputStream(fileDownloadName);
    byte[] b = new byte[1024];
    int i = 0;
    while ((i = in.read(b)) > 0) {
        outp.write(b, 0, i);
    }
    outp.flush();
} catch (Exception e) {
    System.out.println("文件下载失败!");
    e.printStackTrace();
} finally {
    if (in != null) {
        in.close();
        in = null;
    }
     if (outp != null) {
        outp.close();
        outp = null;
        out.clear();
        out = pageContext.pushBody();
    } 
}




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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值