效果图

功能描述

1.使用jquery.form.js实现异步上传功能,并显示上传进度

2.servlet中保存上传的文件到指定文件夹

3.查看已经上传的文件

4.不同文件类型用不同图标显示

下载

https://github.com/houxinlin/ServletUploadFile

项目结构

实现过程

1.Servlet代码

MainServlet.java

MainServlet负责主界面信息,遍历已经上传的文件名,传递给jsp

@WebServlet("/MainServlet")
public class MainServlet extends HttpServlet {
private static final long serialVersionUID = 1L; public MainServlet() {
super();
} protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String path = request.getContextPath();
String basePath = request.getScheme() + "://"
+ request.getServerName() + ":" + request.getServerPort()
+ path + "/"; System.out.println(basePath);
List<String> list =FilesUtils.listDirFiles(Config.UPLOAD_PATH);
Map<String, String> map =new HashMap<>();
for (String string : list) {
map.put(string, string.substring(string.lastIndexOf(".")+1, string.length()) +""); }
request.setAttribute("files", map);
request.setAttribute("basePath", basePath);
request.getRequestDispatcher("upload/index.jsp").forward(request, response); }
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
} }

UploadServlet.java

UploadServlet负责保存文件,如果文件有同名的,则更正

package com.houxinlin.servlets;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths; import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part; /**
* Servlet implementation class UploadServlet
*/
@WebServlet("/UploadServlet")
@MultipartConfig
public class UploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L; /**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
Part part =request.getPart("file");
if(part!=null) {
saveFile(part.getInputStream(),Config.UPLOAD_PATH,part.getSubmittedFileName());
} }
private void saveFile(InputStream is,String rootPath , String name) {
try {
String tempName =name; Path path =Paths.get(rootPath, tempName);
int index=0;
//如果文件存在
if(Files.exists(path)) { while(Files.exists(path)) { name=(++index)+tempName;
path =Paths.get(rootPath, name);
}
System.out.println("文件存在,文件名改正为----"+name);
}
System.out.println("保存---->"+rootPath +File.separatorChar+name);
Files.copy(is, Paths.get(rootPath, name));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} } /**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
} }

辅助类

FilesUtils.java和Configa.java

package com.houxinlin.servlets;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Stream; public class FilesUtils {
public static List<String> listDirFiles(String rootPath){
List<String> list =new ArrayList<>(); Stream<Path> paths;
try {
paths = Files.list(Paths.get(rootPath));
Iterator<Path> item =paths.iterator();
while (item.hasNext()) {
Path path =item.next();
if(!Files.isDirectory(path)) {
list.add(path.getFileName()+"");
}
} } catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return list;
}
}
package com.houxinlin.servlets;

public class Config {
public static final String UPLOAD_PATH="D:\\upload";
}

js

$("#add-file").click(function(param) {
param.stopPropagation();
param.stopPropagation();
$("#upload-layout").css("display", "block")
}) $("#select-file-btn").click(function(param) {
document.getElementById("file-input").click();
})
$("#file-input").change(function() {
$("#select-file-btn label").html($("#file-input").val());
$("#up-btn #progress-value").css("width", 0 +"%");
$("#up-btn .title").html("上传") }); $("#up-btn").click(function(param) {
$(this).css({
"width" : "87%",
});
upload(); }) function upload(param) { $("#upload-form").ajaxSubmit({
success : function(param) {
$("#up-btn .title").html("完成")
},
uploadProgress : function(event, position, total, percentComplete) {
var width =(position/total)*100;
$("#up-btn #progress-value").css("width", width +"%");
$("#up-btn .title").html(+"%")
var value =parseInt(width);
$("#up-btn .title").html(value+"%")
},
fail : function(param) {
$("#up-btn .title").html("失败")
}
}) }

最新文章

  1. 基于Caffe的DeepID2实现(中)
  2. HTML标签-【fieldset】-fieldset
  3. 【转】如何在Windows+VS2005使用最新静态libcurl 7.35.0获取网页数据,支持HTTPS
  4. DropDownList 绑定DataTable并给默认值
  5. HDU 1350
  6. 使用cwRsync实现windows下文件定时同步【转】
  7. EF Code First 数据迁移命令
  8. IMP不到指定的表空间
  9. Hibernate征途(五)之继承映射和组件映射
  10. JSP、JSTL、EL
  11. python去除读取文件中多余的空行
  12. WebService简单搭建和调用
  13. jsp后台取出request请求头
  14. 小程序证书申请FAQ
  15. WEB上传大文件解决方案
  16. 【Android】水平居中 垂直居中 中心居中
  17. 设计模式-生成者模式之c#代码
  18. 【Qt开发】常用控件--QLineEdit
  19. C#单元测试:NUnit详细使用方法
  20. 在雇员表中查找第二高的工资SQL语句助记

热门文章

  1. iOS 声明属性关键字的总结
  2. MYSQL进阶学习笔记二:MySQL存储过程和局部变量!(视频序号:进阶_4-6)
  3. [原创]Java生成Word文档
  4. UVA-10391(字符串检索)
  5. Objective-C中的+initialize和+load
  6. 预处理指令#pragram
  7. BZOJ_4311_向量_线段树按时间分治
  8. Ruby 全局变量,实例变量,类变量
  9. ASP.NET Core MVC 2.x 全面教程_ASP.NET Core MVC 20. Model Binding
  10. AndroidManifest.xml文件详解(uses-feature) (转载)