之前涉及到前台读取本地文件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");
}