效果图

功能描述

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. spring boot 使用Ehcache

    1-引入maven依赖: 2-增加ehcache.xml 3-bootstrap.yml配置ehcache.xml的路径 4-启动类加注解@EnableCaching 5-使用处加注解@Cacheab ...

  2. ActiveMQ 安全认证

    修改配置文件 位置: apache-activemq-5.9.0/conf/ vi activemq.xml 在<broker xmlns="http://activemq.apach ...

  3. codeforcfes Codeforces Round #287 (Div. 2) B. Amr and Pins

    B. Amr and Pins time limit per test 1 second memory limit per test 256 megabytes input standard inpu ...

  4. POJ1087 A Plug for UNIX —— 最大流

    题目链接:https://vjudge.net/problem/POJ-1087 A Plug for UNIX Time Limit: 1000MS   Memory Limit: 65536K T ...

  5. MYSQL初级学习笔记八:MySQL中常用的函数!(视频序号:初级_45-50)

    知识点十:MySQL中的函数(45-50) 数学函数: 名称 描述 CEIL() 进一取整 FLOOR() 舍一取整 MOD 取余数(取摸) POWER() 幂运算 ROUND() 四舍五入 TRUN ...

  6. 网易短信接口集成 nodejs 版

    /* name:网易短信服务集成nodejs版: author:zeq time:20180607 test: // checkValidCode('157****6954','284561').th ...

  7. MYSQL数据库学习----索引和触发器

    一:索引 索引是创建在数据库表上,其作用是提高对表中数据的查询速度. 假设数据库中有一张1000条记录的表格,如果没有创建索引的话,用户想通过查询条件查询,实际上是把整个数据库中1000条记录都读取一 ...

  8. 如何下载WDK

    随着Windows Vista和Windows Server 2008的相继发布,微软的驱动开发工具也进行了相应的更新换代.原来的驱动开发工具包叫做DDK(Driver Develpment Kit) ...

  9. 当你触摸并按住触摸目标时候,禁止系统默认菜单-webkit-touch-call

    当你触摸并按住触摸目标时候,禁止或显示系统默认菜单. -webkit-touch-callout 是一个 不规范的属性(unsupported WebKit property),它没有出现在 CSS ...

  10. 阿里云RDS数据库备份文件恢复到本地mysql数据库

    一.安装mysql和xtrabackup  (1)安装mysql 因为RDS是5.6版本,所以我们本地的mysql数据库要与RDS版本对应. rpm -ivh http://repo.mysql.co ...