转载自:http://www.cnblogs.com/oumyye/p/4234969.html

文件上传几乎是所有网站都具有的功能,用户可以将文件上传到服务器的指定文件夹中,也可以保存在数据库中,本篇主要说明smartupload组件上传。

在讲解smartupload上传前,我们先来看看不使用组件是怎么完成上传的原理的?

废话不多说直接上代码

 
import java.io.*;
import java.util.*;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class FileUploadTools {
private HttpServletRequest request = null; // 取得HttpServletRequest对象
private List<FileItem> items = null; // 保存全部的上传内容
private Map<String, List<String>> params = new HashMap<String, List<String>>(); // 保存所有的参数
private Map<String, FileItem> files = new HashMap<String, FileItem>();
private int maxSize = 3145728; // 默认的上传文件大小为3MB,3 * 1024 * 1024
public FileUploadTools(HttpServletRequest request, int maxSize,
String tempDir) throws Exception { // 传递request对象、最大上传限制、临时保存目录
this.request = request; // 接收request对象
DiskFileItemFactory factory = new DiskFileItemFactory(); // 创建磁盘工厂
if (tempDir != null) { // 判断是否需要进行临时上传目录
factory.setRepository(new File(tempDir)); // 设置临时文件保存目录
}
ServletFileUpload upload = new ServletFileUpload(factory); // 创建处理工具
if (maxSize > 0) { // 如果给的上传大小限制大于0,则使用新的设置
this.maxSize = maxSize;
}
upload.setFileSizeMax(this.maxSize); // 设置最大上传大小为3MB,3 * 1024 * 1024
try {
this.items = upload.parseRequest(request);// 接收全部内容
} catch (FileUploadException e) {
throw e; // 向上抛出异常
}
this.init(); // 进行初始化操作
}
private void init() { // 初始化参数,区分普通参数或上传文件
Iterator<FileItem> iter = this.items.iterator();
IPTimeStamp its = new IPTimeStamp(this.request.getRemoteAddr()) ;
while (iter.hasNext()) { // 依次取出每一个上传项
FileItem item = iter.next(); // 取出每一个上传的文件
if (item.isFormField()) { // 判断是否是普通的文本参数
String name = item.getFieldName(); // 取得表单的名字
String value = item.getString(); // 取得表单的内容
List<String> temp = null; // 保存内容
if (this.params.containsKey(name)) { // 判断内容是否已经存放
temp = this.params.get(name); // 如果存在则取出
} else { // 不存在
temp = new ArrayList<String>(); // 重新开辟List数组
}
temp.add(value); // 向List数组中设置内容
this.params.put(name, temp); // 向Map中增加内容
} else { // 判断是否是file组件
String fileName = its.getIPTimeRand()
+ "." + item.getName().split("\\.")[1];
this.files.put(fileName, item); // 保存全部的上传文件
}
}
}
public String getParameter(String name) { // 取得一个参数
String ret = null; // 保存返回内容
List<String> temp = this.params.get(name); // 从集合中取出内容
if (temp != null) { // 判断是否可以根据key取出内容
ret = temp.get(0); // 取出里面的内容
}
return ret;
}
public String[] getParameterValues(String name) { // 取得一组上传内容
String ret[] = null; // 保存返回内容
List<String> temp = this.params.get(name); // 根据key取出内容
if (temp != null) { // 避免NullPointerException
ret = temp.toArray(new String[] {});// 将内容变为字符串数组
}
return ret; // 变为字符串数组
}
public Map<String, FileItem> getUploadFiles() {// 取得全部的上传文件
return this.files; // 得到全部的上传文件
}
public List<String> saveAll(String saveDir) throws IOException { // 保存全部文件,并返回文件名称,所有异常抛出
List<String> names = new ArrayList<String>();
if (this.files.size() > 0) {
Set<String> keys = this.files.keySet(); // 取得全部的key
Iterator<String> iter = keys.iterator(); // 实例化Iterator对象
File saveFile = null; // 定义保存的文件
InputStream input = null; // 定义文件的输入流,用于读取源文件
OutputStream out = null; // 定义文件的输出流,用于保存文件
while (iter.hasNext()) { // 循环取出每一个上传文件
FileItem item = this.files.get(iter.next()); // 依次取出每一个文件
String fileName = new IPTimeStamp(this.request.getRemoteAddr())
.getIPTimeRand()
+ "." + item.getName().split("\\.")[1];
saveFile = new File(saveDir + fileName); // 重新拼凑出新的路径
names.add(fileName); // 保存生成后的文件名称
try {
input = item.getInputStream(); // 取得InputStream
out = new FileOutputStream(saveFile); // 定义输出流保存文件
int temp = 0; // 接收每一个字节
while ((temp = input.read()) != -1) { // 依次读取内容
out.write(temp); // 保存内容
}
} catch (IOException e) { // 捕获异常
throw e; // 异常向上抛出
} finally { // 进行最终的关闭操作
try {
input.close(); // 关闭输入流
out.close(); // 关闭输出流
} catch (IOException e1) {
throw e1;
}
}
}
}
return names; // 返回生成后的文件名称
}
}
 

上面代码便可以完成无组件上传。

下面开始讲解smartupload

smartupload是由www.jspsmart.com网站开发的一套上传组件包,可以轻松的实现文件的上传及下载功能,smartupload组件使用简单、可以轻松的实现上传文件类型的限制、也可以轻易的取得上传文件的名称、后缀、大小等。
smartupload本身是一个系统提供的jar包(smartupload.jar),用户直接将此包放到classpath下即可,也可以直接将此包拷贝到TOMCAT_HOME\lib目录之中。
下面使用组件完成上传
单一文件上传:

 
<html>
<head><title>smartupload组件上传</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /></head>
<body>
<form action="smartupload_demo01.jsp" method="post" enctype="multipart/form-data">
图片<input type="file" name="pic">
<input type="submit" value="上传">
</form>
</body>
</html>
 

jsp代码:

smartupload_demo01.jsp
 
<%@ page contentType="text/html" pageEncoding="utf-8"%>
<%@ page import="com.jspsmart.upload.*" %>
<html>
<head><title>smartupload组件上传01</title></head> <body>
<%
SmartUpload smart = new SmartUpload() ;
smart.initialize(pageContext) ; // 初始化上传操作
smart.upload(); // 上传准备
smart.save("upload") ; // 文件保存
out.print("上传成功");
%> </body>
</html>
 

批量上传:

html文件

 
<html>
<head><title>smartupload组件上传02</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /></head>
<body>
<form action="smartupload_demo02.jsp" method="post" enctype="multipart/form-data">
图片<input type="file" name="pic1"><br>
图片<input type="file" name="pic2"><br>
图片<input type="file" name="pic3"><br>
<input type="submit" value="上传">
<input type="reset" value="重置">
</form>
</body>
</html>
 

jsp代码

smartupload_demo02.jsp
 
<%@ page contentType="text/html" pageEncoding="utf-8"%>
<%@ page import="com.jspsmart.upload.*"%>
<%@ page import="com.zhou.study.*"%>
<html>
<head><title>smartupload组件上传02</title></head>
<body>
<%
SmartUpload smart = new SmartUpload() ;
smart.initialize(pageContext) ; // 初始化上传操作
smart.upload() ; // 上传准备
String name = smart.getRequest().getParameter("uname") ;
IPTimeStamp its = new IPTimeStamp("192.168.1.1") ; // 取得客户端的IP地址
for(int x=0;x<smart.getFiles().getCount();x++){
String ext = smart.getFiles().getFile(x).getFileExt() ; // 扩展名称
String fileName = its.getIPTimeRand() + "." + ext ;
smart.getFiles().getFile(x).saveAs(this.getServletContext().getRealPath("/")+"upload"+java.io.File.separator + fileName) ;
}
out.print("上传成功");
%>
</body>
</html>
 

注意:在TOMCAT_HOME/项目目录下建立upload文件夹才能正常运行!

简单上传操作上传后的文件名称是原本的文件名称。可通过工具类重命名。

另附上重命名工具类。

 
package com.zhou.study ;
import java.text.SimpleDateFormat ;
import java.util.Date ;
import java.util.Random ;
public class IPTimeStamp {
private SimpleDateFormat sdf = null ;
private String ip = null ;
public IPTimeStamp(){
}
public IPTimeStamp(String ip){
this.ip = ip ;
}
public String getIPTimeRand(){
StringBuffer buf = new StringBuffer() ;
if(this.ip != null){
String s[] = this.ip.split("\\.") ;
for(int i=0;i<s.length;i++){
buf.append(this.addZero(s[i],3)) ;
}
}
buf.append(this.getTimeStamp()) ;
Random r = new Random() ;
for(int i=0;i<3;i++){
buf.append(r.nextInt(10)) ;
}
return buf.toString() ;
}
public String getDate(){
this.sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS") ;
return this.sdf.format(new Date()) ;
}
public String getTimeStamp(){
this.sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS") ;
return this.sdf.format(new Date()) ;
}
private String addZero(String str,int len){
StringBuffer s = new StringBuffer() ;
s.append(str) ;
while(s.length() < len){
s.insert(0,"0") ;
}
return s.toString() ;
}
public static void main(String args[]){
System.out.println(new IPTimeStamp().getIPTimeRand()) ;
}
}
 

附上使用方法:

 
<html>
<head><title>smartupload上传文件重命名</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> </head>
<body>
<form action="smartupload_demo03.jsp" method="post" enctype="multipart/form-data">
姓名<input type="text" name="uname"><br>
照片<input type="file" name="pic"><br>
<input type="submit" value="上传">
<input type="reset" value="重置">
</form>
</body>
</html>
 

Jsp代码:

smartupload_demo03.jsp
 
<%@ page contentType="text/html" pageEncoding="utf-8"%>
<%@ page import="com.jspsmart.upload.*" %>
<%@ page import="com.zhou.study.*"%>
<html>
<head><title>smartupload</title></head>
<body>
<%
SmartUpload smart = new SmartUpload() ;
smart.initialize(pageContext) ; //初始化上传操作
smart.upload() ; // 上传准备
String name = smart.getRequest().getParameter("uname") ;
String str = new String(name.getBytes("gbk"), "utf-8"); //传值过程中出现乱码,在此转码
IPTimeStamp its = new IPTimeStamp("192.168.1.1") ; // 取得客户端的IP地址
String ext = smart.getFiles().getFile(0).getFileExt() ; // 扩展名称
String fileName = its.getIPTimeRand() + "." + ext ;
smart.getFiles().getFile(0).saveAs(this.getServletContext().getRealPath("/")+"upload"+java.io.File.separator + fileName) ;
out.print("上传成功");
%> <h2>姓名:<%=str%></h2>
<img src="upload/<%=fileName%>">
</body>
</html>
 

java基础篇---文件上传(组件)的更多相关文章

  1. java基础篇---文件上传(commons-FileUpload组件)

    上一篇讲解了smartupload组件上传,那么这一篇我们讲解commons-FileUpload组件上传 FileUpload是Apache组织(www.apache.org)提供的免费的上传组件, ...

  2. java基础篇---文件上传(smartupload组件)

    文件上传几乎是所有网站都具有的功能,用户可以将文件上传到服务器的指定文件夹中,也可以保存在数据库中,本篇主要说明smartupload组件上传. 在讲解smartupload上传前,我们先来看看不使用 ...

  3. JAVA基础篇—文件上传下载

    /index.jsp <%@ page language="java" contentType="text/html; charset=UTF-8" pa ...

  4. 【Java】JavaWeb文件上传和下载

    文件上传和下载在web应用中非常普遍,要在jsp环境中实现文件上传功能是非常容易的,因为网上有许多用java开发的文件上传组件,本文以commons-fileupload组件为例,为jsp应用添加文件 ...

  5. Commons FileUpload文件上传组件

    Java实现的文件上传组件有好几种,其中最为“官方”的要数Apache Commons库中的FileUpload了吧. 页面 <form method="POST" enct ...

  6. Bootstrap fileinput.js,最好用的文件上传组件

    本篇介绍如何使用bootstrap fileinput.js(最好用的文件上传组件)来进行图片的展示,上传,包括springMVC后端文件保存. 一.demo   二.插件引入 <link ty ...

  7. vue大文件上传组件选哪个好?

    需求:项目要支持大文件上传功能,经过讨论,初步将文件上传大小控制在500M内,因此自己需要在项目中进行文件上传部分的调整和配置,自己将大小都以501M来进行限制. 第一步: 前端修改 由于项目使用的是 ...

  8. Java FtpClient 实现文件上传服务

    一.Ubuntu 安装 Vsftpd 服务 1.安装 sudo apt-get install vsftpd 2.添加用户(uftp) sudo useradd -d /home/uftp -s /b ...

  9. java web(四)文件上传与下载

     一.文件上传原理 1.在TCP/IP中,最早出现的文件上传机制是FTP ,它是将文件由客户端发送到服务器的标准机制:但是在jsp使用过程中不能使用FTP方法上传文件,这是由jsp运行机制所决定. 通 ...

随机推荐

  1. Codeforces 145A-Lucky Conversion(规律)

    A. Lucky Conversion time limit per test 2 seconds memory limit per test 256 megabytes input standard ...

  2. git 配置用户名email地址,设置密码

  3. C#数据池

    //ThreadPool(线程池)是一个静态类,它没有定义任何的构造方法(),我们只能够使用它的静态方法,这是因为,这是因为ThreadPool是托管线程池(托管线程池http://msdn.micr ...

  4. [AngularFire 2 ] Hello World - How To Write your First Query using AngularFire 2 List Observables ?

    In this lesson we are going to use AngularFire 2 for the first time. We are going to configure the A ...

  5. 如何把canvas元素作为网站背景总结详解

    如何把canvas元素作为网站背景总结详解 一.总结 一句话总结:最简单的做法是绝对定位并且z-index属性设置为负数. 1.如何把canvas元素作为网站背景的两种方法? a.设置层级(本例代码就 ...

  6. 结合Wireshark捕获分组深入理解TCP/IP协议栈

    摘要:     本文剖析了浏览器输入URL到整个页面显示的整个过程,以百度首页为例,结合Wireshark俘获分组进行详细分析整个过程,从而更好地了解TCP/IP协议栈.   一.俘获分组 1.1 准 ...

  7. iOS开发webView的使用一

    #import "ViewController.h" @interface ViewController () @property (weak, nonatomic) IBOutl ...

  8. OpenStack 之 Nova Compute 的代码结构图

    nova-compute 的代码结构图 如上图所看到的, 类图中最重要的三个Category Manager: 核心的业务类.提供实际的业务操作.比如启动虚拟机等等. Service: 每一个serv ...

  9. spring+aspectJ的实现

    AspectJ:(Java社区里最完整最流行的AOP框架) spring自身也有一套AOP框架,但相比较于AspectJ,更推荐AspectJ 在Spring2.0以上版本中,可以使用基于Aspect ...

  10. [React Router v4] Use the React Router v4 Link Component for Navigation Between Routes

    If you’ve created several Routes within your application, you will also want to be able to navigate ...