1.利用JS点一次 加一个上传框
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<script type="text/javascript">
function addOne() {
var fdiv=document.getElementById("fdiv");
fdiv.innerHTML+='<div><input type="file" name="file1" /><input type="button" value="删除" onclick="delOne(this)" id="delBut"></div>';
}
function delOne(obj){
obj.parentNode.parentNode.removeChild(obj.parentNode);
}
</script>
</head>
<body>
<h1>文件上传</h1><hr>
<input type="button" value="加一个" onclick="addOne()" id="addBut">
<form action="${pageContext.request.contextPath }/servlet/UploadServlet" method="POST" enctype="multipart/form-data">
描述信息1:<input type="text" name="description1"/>
描述信息2:<input type="text" name="description2"/>
<div id="fdiv"></div>
<input type="file" name="file1" />
<input type="submit" value="上传"/>
</form>
</body>
</html>
当我们上传文件很多的时候难免会有重名的,所以我们要对他们的位置进行设置:
利用UUID进行重命名,这样在同一个文件夹下确实不会重名了,但都放在一个文件夹里太多了影响读写性能,我们要分目录,根据后缀根据日期。。。。
今天我们用到的是根据hash值来分:
String filename = item.getName();
String uuidName = UUID.randomUUID().toString() + "_"
+ filename;
int hash = uuidName.hashCode();
String hashStr = Integer.toHexString(hash);//转成十六进制(长度为8) 每一位生成一个文件夹(每一级最多16个目录)
char[] hss = hashStr.toCharArray();//转为char型数组
String path = this.getServletContext().getRealPath(
"WEB-INF/upload");
for (char c : hss) {
path += "/" + c;
}
new File(path).mkdirs();
InputStream in = item.getInputStream();
OutputStream out = new FileOutputStream(new File(path,
uuidName));
IOUtils.In2Out(in, out);
IOUtils.close(in, out);
// --删除临时文件
item.delete();
upload temp 不要直接放在 web-Root下 ,加入某人上传了一个恶意的jsp可以通过 /Day15/uplod/1.jsp访问到 jsp中可以嵌入入侵代码,所以我们可以将upload temp 放到 WEB-INF目录下,保护起来(WEB-INF我们是访问不到的)
总结下:
文件存放应该注意的问题:
1.upload文件夹和temp文件夹都要放在web-inf目录下保护起来,防止上传入侵和访问其他用户上传资源的问题
2.文件名要拼接uuid保证唯一
3.文件要分目录存储保证同一目录下不要有过多的文件,分目录的算法有很多,介绍了一种根据hash值分目录算法