java_post接收文件流_异或加密保存服务器

之前涉及到前台读取本地文件post到后台处理文件流,这里简单记录下

protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		// response.getWriter().append("Served at: ").append(request.getContextPath());

		// 获取get参数whichFolder,如:whichFolder=xxx\2019-01-27
		String bothPath = new String(request.getParameter("whichFolder").getBytes("ISO8859-1"), "UTF-8");

		// 通过反斜杠来分隔文件夹
		String[] folderArr = bothPath.split("\\\\");
		
		//获取路径
		String allPath = request.getSession().getServletContext().getRealPath("") + "\\upload";
		
		for(int i = 0; i < folderArr.length; i++) {
			System.out.println(folderArr[i]);
			allPath = allPath + "\\" + folderArr[i];
			//分别检查是否存在该文件
			File dir = new File(allPath);
			if(dir.exists()) {
				continue;
			}else {
				dir.mkdir();
			}
		}
		
		//创建名称
		String fileName = UUID.randomUUID().toString();
		
		//获取post上来的文件流并转化为buffer格式
		InputStream postFile = request.getInputStream(); 
		BufferedInputStream postBufferFile = new BufferedInputStream(postFile);
		
		//准备接收流容器
		BufferedOutputStream writeToFile = new BufferedOutputStream(
				new FileOutputStream(new File(allPath + "\\" + fileName + ".pdf")));
		
		//写入到指定文件
		int len = 0;
		byte buf[] = new byte[1024];
		while ((len = postBufferFile.read(buf)) != -1) {
			for (int i = 0; i < len; i++) {
				buf[i] ^= 1234; //对每个字节进行异或
			}
			writeToFile.write(buf,0,len);
		}
		//写入完成 关闭所有涉及的流
		postFile.close();
		postBufferFile.close();
		writeToFile.close();
		File myFile = new File(allPath + "\\" + fileName + ".pdf");
		
		long myFileSize = 0;
		if(myFile.exists() && myFile.isFile()) {
			myFileSize = myFile.length();
		}else {
			myFileSize = 0;
		}
		
		/* 返回json给客户端 */
		JSONObject backJSON = new JSONObject();
		backJSON.put("filename", fileName);
		backJSON.put("filepath","\\upload\\" + bothPath + "\\" +fileName);
		backJSON.put("filesize",myFileSize);
		response.setContentType("application/json");
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		out.write(backJSON.toString());
		System.out.println(backJSON);
		out.close();
		
		//System.out.println("servlet中路径:"+request.getSession().getServletContext().getRealPath("") + "upload");
	}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值