java commons-fileupload servlet 多文件上传
commons-fileupload servlet 多文件上传
需要引入的 jar 包。
commons-fileupload-1.3.2.jar
commons-io-2.2.jar
工程路劲:查看源码
JSP 页面:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>批量上传</title>
</head>
<body>
<form name="uploadForm" method="post" action="UoloadServlet" enctype="multipart/form-data">
<table border="1">
<thead>
<tr>
<th>名称</th>
<th>文件</th>
</tr>
</thead>
<tbody>
<c:forEach begin="1" end="10" var="i">
<tr>
<td>文件${i}</td>
<td><input type="file" name="file"></td>
</tr>
</c:forEach>
</tbody>
</table>
<input type="submit" name="submit" value="开始上传">
</form>
</body>
</html>
servlet 页面
package com.servlet;
import java.io.File;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.util.FileUtil;
/**
* Servlet implementation class uoloadServlet
*/
public class UoloadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public UoloadServlet() {
super();
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// 文件上传的路径,这里设置的是服务器项目根路径下的 IMG 目录
String filePath = request.getSession().getServletContext().getRealPath("/")+ "IMG/";
// 获取照片上传工具类,并且批量上传照片文件
List<File> files = FileUtil.getInstance(filePath).upload(request);
// 将上传成功照片的照片传值到页面
request.setAttribute("files", files);
request.getRequestDispatcher("list.jsp").forward(request, response);
}
}
FileUtil.java
package com.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class FileUtil {
// 文件上传路径
private static String UPLOAD_PATH = null;
/**
* @author Duke 静态内部类,实例化工具类
*/
private static class LazyHolder {
private static final FileUtil FILEUTIL = new FileUtil();
}
/**
* 私有构造函数
*/
private FileUtil() {
}
/**
* 获取工具类实例
*
* @return FileUploadUtil 实例
*/
public static FileUtil getInstance(String uploadPath) {
UPLOAD_PATH = uploadPath;
return LazyHolder.FILEUTIL;
}
/**
* 文件批量上传
*
* @param request
* @param uploadPath
*
*/
public List<File> upload(HttpServletRequest request) {
// 用于存放上传成功的照片
List<File> files = new ArrayList<File>();
try {
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List<FileItem> items = upload.parseRequest(request);
for (FileItem fileItem : items) {
// 获得文件名,包括文件路径
String fileFullName = fileItem.getName();
if (fileFullName != null && fileFullName != "" && fileItem.getSize() > 0) {
// 获取文件路径
String fileName = new File(fileFullName).getName();
// 创建文件
File savedFile = new File(UPLOAD_PATH, fileName);
// 如果文件所在文件夹不存在的话,新建文件夹
if (!savedFile.getParentFile().exists()) {
savedFile.getParentFile().mkdirs();
}
// 写入文件
fileItem.write(savedFile);
files.add(savedFile);
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return files;
}
/**
* 文件下载
*
* @param filePath
* @throws IOException
* @throws Exception
*/
public void downLoadFile(String filePath, HttpServletResponse response) throws IOException {
// 处理中文乱码问题
filePath = new String(filePath.getBytes("ISO-8859-1"), "UTF-8");
downLoadFile(new File(filePath), response);
}
/**
* 文件下载
*
* @param file
* @throws IOException
*/
public void downLoadFile(File file, HttpServletResponse response) throws IOException {
if (file.exists()) {
response.reset();
response.setContentType("application/x-download");
response.addHeader("Content-Disposition", "attachment; filename=\"" + URLEncoder.encode(file.getName(), "UTF-8"));
// 输出文件字节流
writeBufferByte(file, response);
}
}
/**
* 输出照片字节流
*
* @throws IOException
*/
public void outputImgByte(String filePath, HttpServletResponse response) throws IOException {
// 处理中文乱码问题
filePath = new String(filePath.getBytes("ISO-8859-1"), "UTF-8");
outputImgByte(new File(filePath), response);
}
/**
* 输出照片字节流
*
* @throws IOException
*/
public void outputImgByte(File file, HttpServletResponse response) throws IOException {
// 文件存在的情况下输出文件
if (file.exists()) {
// 设置相应信息的类型
response.setContentType("image/jpeg");
// 输出文件字节流
writeBufferByte(file, response);
}
}
/**
* 输出文件字节流
*
* @param file
* @param response
* @throws IOException
*/
private void writeBufferByte(File file, HttpServletResponse response) throws IOException {
// 一次读 2048 个字节
byte[] buffer = new byte[2048];
// 获取照片流
FileInputStream fos = new FileInputStream(file);
int count;
while ((count = fos.read(buffer)) > 0) {
// 输出照片流
response.getOutputStream().write(buffer, 0, count);
}
fos.close();
}
}
java commons-fileupload servlet 多文件上传的更多相关文章
- Servlet实现文件上传
一.Servlet实现文件上传,需要添加第三方提供的jar包 下载地址: 1) commons-fileupload-1.2.2-bin.zip : 点击打开链接 2) commons- ...
- Servlet实现文件上传,可多文件上传
一.Servlet实现文件上传,需要添加第三方提供的jar包 接着把这两个jar包放到 lib文件夹下: 二: 文件上传的表单提交方式必须是POST方式, 编码类型:enctype="mul ...
- jsp+servlet实现文件上传下载
相关素材下载 01.jsp <%@ page language="java" contentType="text/html; charset=UTF-8" ...
- Java实现一个简单的文件上传案例
Java实现一个简单的文件上传案例 实现流程: 1.客户端从硬盘读取文件数据到程序中 2.客户端输出流,写出文件到服务端 3.服务端输出流,读取文件数据到服务端中 4.输出流,写出文件数据到服务器硬盘 ...
- Java 客户端操作 FastDFS 实现文件上传下载替换删除
FastDFS 的作者余庆先生已经为我们开发好了 Java 对应的 SDK.这里需要解释一下:作者余庆并没有及时更新最新的 Java SDK 至 Maven 中央仓库,目前中央仓库最新版仍旧是 1.2 ...
- 配置servlet支持文件上传
Servlet3.0为Servlet添加了multipart配置选项,并为HttpServletRequest添加了getPart和getParts方法获取上传文件.为了使Servlet支付文件上传需 ...
- Java进阶学习:将文件上传到七牛云中
Java进阶学习:将文件上传到七牛云中 通过本文,我们将讲述如何利用七牛云官方SDK,将我们的本地文件传输到其存储空间中去. JavaSDK:https://developer.qiniu.com/k ...
- 使用FileUpload实现Servlet的文件上传
简介 FileUpload 是 Apache commons下面的一个子项目,用来实现Java环境下的文件上传功能. FileUpload链接 FileUpload 是基于Apache的Commons ...
- servlet web文件上传
web文件上传也是一种POST方式,特别之处在于,需设置FORM的enctype属性为multipart/form-data. 并且需要使用文件域. servlet的代码比较关键是这几句: // 使用 ...
随机推荐
- NTP时钟调整策略
一. 问题背景 天威视讯项目3月底发生了一次点播出现节目请求超时的情况,在查询故障的过程中,发现MAP服务器操作系统的时钟被向前调整了11秒,姑且不论是否是这个原因导致的故障,但每台服务 ...
- linux文本查看与搜索
1. cat-->全文本显示 cat file #全文本显示在终端 cat -n file #显示全文本,并显示行号 cat file1 file2 >file3 #将file1 file ...
- java 异常处理try+catch
在整个异常处理机制中,异常在系统中进行传递,传递到程序员认为合适的位置,就捕获到该异常,然后进行逻辑处理,使得项目不会因为出现异常而崩溃.为了捕获异常并对异常进行处理,使用的捕获异常以及处理的语法格式 ...
- js try{}catch(e){}的理解
程序开发中,编程人员经常要面对的是如何编写代码来响应错误事件的发生,即例外处理(exception handlers).如果例外处理代码设计得周全,那么最终呈现给用户的就将是一个友好的界面.否则,就会 ...
- [CF1202B] You Are Given a Decimal String(最短路)
Description 今天突然想来发一篇博客防死 [Portal][https://vjudge.net/problem/2650668/origin] 定义被x-y生成器生成的序列为, 一开始有一 ...
- Codeforces 500C New Year Book Reading
C. New Year Book Reading time limit per test 2 seconds memory limit per test 256 megabytes input sta ...
- poj2752Seek the Name, Seek the Fame(next数组)
题目传送门 Seek the Name, Seek the Fame Time Limit: 2000MS Memory Limit: 65536K Total Submissions: 2439 ...
- 六、hibernate表与表之间的关系(多对多关系)
多对多关系 创建实体类和对应映射文件 Student.java package com.qf.entity; import java.util.HashSet; import java.util.Se ...
- 箭头函数与普通function的区别
1. 箭头函数没有自己的this,它里面的this是继承所属上下文中的this,而且使用call与apply都无法改变 let obj = { name: 'obj' } function fn1() ...
- sql 根据身份证判断年龄是否小于18岁
SELECT *, Age= datediff(yy,cast(case when substring(PersonalId,,) ') /*若第7位不是'1'或'2'则表示是15位身份证编码规则*/ ...