一、导入jar包
二、java应用:
(1)文件上传
国际化:
hytc.properties
uploaderror=The field upfile exceeds its maximum permitted size of {0} bytes
msg=You can only upload {0} form,can't upload {1} form file
hytc_zh.properties
uploaderror=u5141u8BB8u4E0Au4F20u6587u4EF6u7684u6700u5927u503Cu4E3A {0} u5B57u8282
msg=u53EAu5141u8BB8u4E0Au4F20u7684u6587u4EF6u683Cu5F0Fu662F {0} uFF0Cu4E0Du5141u8BB8u4E0Au4F20 {1} u683Cu5F0Fu7684u6587u4EF6
hytc_en.properties
uploaderror=The field upfile exceeds its maximum permitted size of {0} bytes
msg=You can only upload {0} form,can't upload {1} form file
index.jsp页面
<div>
<c:if test="${maxsize!=null }">
<fmt:bundle basename="hytc">
<fmt:message key="uploaderror">
<fmt:param value="${maxsize }"></fmt:param>
</fmt:message>
</fmt:bundle>
</c:if>
<c:if test="${contenttype!=null }">
<fmt:bundle basename="hytc">
<fmt:message key="msg">
<fmt:param value="${filetypes }"/>
<fmt:param value="${contenttype }"/>
</fmt:message>
</fmt:bundle>
</c:if>
</div>
<div>
<h3>文件上传案例</h3>
<form method="post" enctype="multipart/form-data" action="${pageContext.request.contextPath }/upload.do">
<table>
<tr>
<td>File to load:</td>
<td><input type="file" name="upfile"></td>
</tr>
<tr>
<td>File to load:</td>
<td><input type="file" name="upfiles"></td>
</tr>
<tr>
<td>Notes about the file:</td>
<td><input type="text" name="note"/></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="上传"/>
</td>
</tr>
</table>
</form>
</div>
<div>
<a href="${pageContext.request.contextPath }/down.do?oper=pre">下载资源</a>
</div>
</body>
上传的Java代码及注意事项:
注意1:编码方式
注意2:删除临时文件
注意3:不同浏览器的设置
注意4:上传的目录设置
注意5:查看进度
注意6:设置上传文件最大字节数
注意7:限制文件上传格式
// 允许上传文件的最大值(单个文件)
private long maxsize = 2 * 1024 * 1024;
// 允许上传的文件类型
private List fileTypes = Arrays.asList("image/png", "image/jpeg", "image/gif", "image/bmp");
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//设置编码方式
request.setCharacterEncoding("UTF-8");
// multipart/form-data
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
// 判断是否是上传文件
if (isMultipart) {
// 创建FileItem <input type="text" name="upfile"> 工厂对象
DiskFileItemFactory factory = new DiskFileItemFactory();
// 获取ServletContext对象
ServletContext servletContext = this.getServletConfig().getServletContext();
// 获取上下文 文件的临时目录
File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
// 设置上传文件临时目录
factory.setRepository(repository);
// 创建文件上传的处理对象
ServletFileUpload upload = new ServletFileUpload(factory);
//设置编码方式
upload.setHeaderEncoding("UTF-8");
//创建一个进度监听对象
ProgressListener progressListener = new ProgressListener(){
/**
* 进度发生变化的时候处理的方法
* pBytesRead 上传的进度
* pContentLength 总大小
* pItems 那个条目 1
*/
public void update(long pBytesRead, long pContentLength, int pItems) {
System.out.println("We are currently reading item " + pItems);
if (pContentLength == -1) {
System.out.println("So far, " + pBytesRead + " bytes have been read.");
} else {
System.out.println("So far, " + pBytesRead + " of " + pContentLength
+ " bytes have been read.");
}
}
};
//设置监听
upload.setProgressListener(progressListener);
try {
// 根据upload对象.parseRequest(request) 每个请求文件条目对象
List<FileItem> items = upload.parseRequest(request);
System.out.println("条目的大小数量:::::"+items.size());
upload.setFileSizeMax(maxsize);// 字节
// 根据upload对象.parseRequest(request) 每个请求文件条目对象
List<FileItem> items = upload.parseRequest(request);
// 先遍历一次
for (int index = 0; index < items.size(); index++) {
// 获取具体的一个条目
FileItem fileItem = items.get(index);
// 是否是上传的<input type='file'>控件
if (!fileItem.isFormField()) {
String contentType = fileItem.getContentType();
System.out.println(contentType);
/**
* application/vnd.ms-excel,image/png,image/jpeg,image/
* gif,image/bmp
*/
// 判断
if (!fileTypes.contains(contentType)) {
request.setAttribute("msg",
"文件上传只允许上传" + fileTypes.toString()
+ ",不允许上传" + contentType);
request.getRequestDispatcher("./index.jsp")
.forward(request, response);
return;
}
}
}
// 获取集合的迭代器对象
Iterator<FileItem> iter = items.iterator();
// 判断是含有下一个条目
while (iter.hasNext()) {
// 获取条目对象
FileItem item = iter.next();
// 判断这个item条目是否是普通的文本条目<input type="text" name="note">
if (item.isFormField()) {
String name = item.getFieldName(); // 获取name的名称 note
String value = item.getString(); // 获取输入框中输入的value值
//转码 解决乱码问题
value = new String(value.getBytes("ISO8859-1"),"UTF-8");
System.out.println(name + "-----" + value);
} else {
// <input type="file" name="upfile">
String fileName = item.getName(); // 获取文件的名称
//1427791277139_C:UsershjDesktop1104报到情况统计.xls
int index = fileName.lastIndexOf("\");
File file =null;
//保存路径地址
String path = request.getServletContext().getRealPath("/WEB-INF/upload");
//判断是否含有
if(index==-1){
// 写入到磁盘上 firefox浏览器的文件创建
//file= new File(parentFile,System.currentTimeMillis()+"_"+fileName);
file = createSaveFile(path, fileName);
}else{
//IE浏览器的处理方式
//file= new File(parentFile,System.currentTimeMillis()+"_"+fileName.substring(index+1));
file = createSaveFile(path,fileName.substring(index + 1));
}
// 输出流
OutputStream os = new FileOutputStream(file);
// 读取文件
InputStream is = item.getInputStream();
// 定义缓冲区
byte buffer[] = new byte[1024];
// 定义读取的长度
int len = 0;
// 循环读取
while ((len = is.read(buffer)) != -1) {
os.write(buffer, 0, len);// 写入
}
// 释放资源
os.flush();
os.close();
is.close();
//删除临时文件
item.delete();
}
}
//上传成功
//下载此网站的所有资源
request.getRequestDispatcher("./down.do?oper=pre").forward(request, response);
} catch (FileUploadBase.FileSizeLimitExceededException fsle) {
request.setAttribute("maxsize", maxsize);
request.getRequestDispatcher("./index.jsp").forward(request,
response);
}catch (FileUploadException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
System.out.println("没有上传文件");
}
}
/**
* 文件名称及文件父目录 拼接而成
*
* @return
*/
public File createSaveFile(String path, String fileName) {
File file = null;
// 代表对象的内存存储地址 0x888aBF; 4321 0xf;
int hashCode = fileName.hashCode();
int dir1 = hashCode & 0xf; // 目录1
int dir2 = (hashCode >> 4) & 0xf;// 目录2
// 根据算法生成目录结构
path = path + "\" + dir1 + "\" + dir2;
// 父目录对象
File parentFile = new File(path);
// 判断父目录是否存在
if (!parentFile.exists()) {
parentFile.mkdirs();
}
// 创建文件对象
file = new File(parentFile, System.currentTimeMillis() + "_" + fileName);
return file;
}
(2)文件下载:
下载的jsp页面:
<!-- 1.下载方式 -->
<a href="${pageContext.request.contextPath}/images/1.png">1.png</a>
<h2>所有下载的资源</h2>
<c:forEach var="file" items="${map}">
<div>
<%-- <a href="${file.key}">${file.value}</a> --%>
<a href="${pageContext.request.contextPath}/down.do?oper=down&path=${file.key}">${file.value }</a>
</div>
</c:forEach>
下载的Java代码及注意事项:
public class DownLoadServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");//tomcat8
String oper = request.getParameter("oper");
if("pre".equals(oper)){
//找到所有的资源文件 WEB-INF/upload/
String path=request.getServletContext().getRealPath("/WEB-INF/upload");
System.out.println("path:="+path);
//创建父目录对象
File file = new File(path);
//遍历父目录
iteratorFiles(file);
//遍历这里所有文件 把这些文件存储到什么位置
request.setAttribute("map", map);
//转发到下载页面操作
request.getRequestDispatcher("./down.jsp").forward(request, response);
}else if("down".equals(oper)){
//获取下载文件的地址 /WEB-INF/upload+"----"
String path = request.getParameter("path");
//获取指定下载的文件地址
String filePath=request.getServletContext().getRealPath(path);
System.out.println("filepath=:"+filePath);
//创建文件对象
File file = new File(filePath);
//创建文件的输入流对象
InputStream is = new FileInputStream(file);
//设置响应的类型
response.setContentType("application/x-msdownload");
//设置相应的头
response.setHeader("Content-Disposition", "attachment;filename="+URLEncoder.encode(file.getName().substring(file.getName().lastIndexOf("_")+1), "UTF-8"));//防止乱码
//获取输出流对象
OutputStream os = response.getOutputStream();
//缓冲区
byte buffer[]= new byte[1024];
//读取的长度
int len=0;
//循环读取
while((len=is.read(buffer))!=-1){
os.write(buffer, 0, len);//写入
}
//释放资源
os.close();
is.close();
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doGet(request, response);
}
//创建存储文件的map集合对象
private Map<String,String> map = new TreeMap<String, String>();
/**
* 遍历文件
* @param file
*/
private void iteratorFiles(File file) {
//得到此文件下面的所有文件
File files[]=file.listFiles();
for(File f:files){
if(f.isDirectory()){
iteratorFiles(f);//递归
}else {
// 获取文件名称
String fileName = f.getName();
fileName = fileName.substring(fileName.indexOf("_") + 1);
// 获取文件的路径
String path = f.getPath();
path = path.substring(path.indexOf("\WEB-INF"));
// 替换字符
path = path.replace('\', '/');
// 存入到map集合中
map.put(path, fileName);
}
}
}
}
效果:
上传其他格式的文件后
下载