效果图

功能描述

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("失败")
}
}) }

servlet上传文件+上传进度显示的更多相关文章

  1. Spring Boot上传文件(带进度条)

    Spring Boot 上传文件(带进度条)# 配置文件 spring: freemarker: template-loader-path: classpath:/static/ ##Spring B ...

  2. 使用jsp/servlet简单实现文件上传与下载

    使用JSP/Servlet简单实现文件上传与下载    通过学习黑马jsp教学视频,我学会了使用jsp与servlet简单地实现web的文件的上传与下载,首先感谢黑马.好了,下面来简单了解如何通过使用 ...

  3. HTML5 jQuery+FormData 异步上传文件,带进度条

    <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <link href ...

  4. 【Demo Project】AjaxSubmit+Servlet表单文件上传和下载

    一.背景 前段时间公司要求我做一个上传和下载固件的页面,以备硬件产品在线升级,现在我把这部分功能抽取出来作为一个Demo Project给大家分享. 话不多说,先看项目演示 --> 演示  源码 ...

  5. python 全栈开发,Day86(上传文件,上传头像,CBV,python读写Excel,虚拟环境virtualenv)

    一.上传文件 上传一个图片 使用input type="file",来上传一个文件.注意:form表单必须添加属性enctype="multipart/form-data ...

  6. 将Windows上的文件上传到Linux上

    下载一个SSH Secure Shell Client即可. SSHSecureShellClient-3.2.9下载地址: 免费下载地址在 http://linux.linuxidc.com/ 用户 ...

  7. 打造 html5 文件上传组件,实现进度显示及拖拽上传,支持秒传+分片上传+断点续传,兼容IE6+及其它标准浏览器

    老早就注册了博客园帐号,昨天才发现,连博客都没开,Github也是一样,深觉惭愧,赶紧潜个水压压惊`(*∩_∩*)′ 言归正传.大概许多人都会用到文件上传的功能,上传的库貌似也不少,比如(jQuery ...

  8. jquery ajax php 无刷新上传文件 带 遮罩 进度条 效果的哟

    在很多项目中都会叫用户上传东西这些的,自从接触了jquery 和ajax之后就不管做什么,首先都会想到这个,我这个人呢?是比较重视客户体验的,这次我这边负责的是后台板块,然后就有一块是要求用户上传照片 ...

  9. Servlet实现图片文件上传

    1.首先要导入以下两个jar包: commons-fileupload-1.2.1.jarcommons-io-1.4.jar 2.jsp文件:index.jsp <%@ page langua ...

随机推荐

  1. SVN地址正确,能在网页打开,但是检出失败解决方法

    TortoiseSVN缓存问题 右键点击TortoiseSVN -> Settings -> Saved Data, 点击个个“Clear”按钮,把本地缓存都清除了,点击“确定”: 再重新 ...

  2. redis09---redis 服务器端命令

    redis 服务器端命令 db0,db1,db2是数据库,外层是服务器,服务器下面有20个数据库. :>time ) "" //多少秒 ) "" //多少 ...

  3. UVAlive 6611 Alice's Print Service 二分

    Alice is providing print service, while the pricing doesn't seem to be reasonable, so people using h ...

  4. atexit函数的使用【学习笔记】

    #include "apue.h" static void my_exit1(void); static void my_exit2(void); int main(void) { ...

  5. [原创]JAVA获取word表格中数据的方案

    上一个项目的开发中需要实现从word中读取表格数据的功能,在JAVA社区搜索了很多资料,终于找到了两个相对最佳的方案,因为也得到了不少网友们的帮助,所以不敢独自享用,在此做一个分享. 两个方案分别是: ...

  6. 关于将word转化为pdf 文件调用jacob 包

    用jacob. 先到官方网站上去下载:http://sourceforge.net/project/showfiles.php?group_id=109543&package_id=11836 ...

  7. [Selenium] Selenium find Element Examples

    ---> 1. By.id  以百度主页为例 <span classs = "bg s_ipt_wr"> <input type = "text& ...

  8. HNOI2017 day1 T3 礼物

    题目大意: 我的室友最近喜欢上了一个可爱的小女生.马上就要到她的生日了,他决定买一对情侣手环,一个留给自己,一个送给她.每个手环上各有 n 个装饰物,并且每个装饰物都有一定的亮度.但是在她生日的前一天 ...

  9. excel的部分使用方法

    第一行数据填充下面所有行的快捷键,ctrl+d 两个表关联替换:=VLOOKUP(H1576,Sheet3!$B$2:$C$315,2,0) 取消下拉框:数据>数据有效性>全部清除 快捷选 ...

  10. 洛谷 - P1987 - 摇钱树 - dp - 贪心

    https://www.luogu.org/problemnew/show/P1987 这道题,假如是n==k,也就是把所有的树都砍完,我就知道要贪心去做,因为树给的初始金币是固定的,每天掉金币,当然 ...