在web项目中,文件的上传是被经常使用的功能,比如上传文件或者上传图像等等,因此,文件的上传学习也是一个必须要掌握的基本知识点,下面我使用struts2来演示文件的简单上传实现。
1.开发环境
- myecplise10
- jre7.0
- sturts2.0
2.项目的源码
2.1web.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<display-name></display-name>
<!--在配置struts2的时候过滤器的标签是一定要有的-->
<filter>
<filter-name>struts2</filter-name>
<filter-class> org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
2.2 struts.xml文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
<package name="upload" namespace="/" extends="struts-default">
<action name="upload_*" class="com.wh.upload.FileUploadAction" method="{1}">
<!-- 配置拦截器 -->
<interceptor-ref name="defaultStack">
<!-- 最大接受文件字节数 -->
<param name="fileUpload.maximumSize">1024*1024*2</param>
<!-- 文件上传允许的类型 -->
<param name="fileUpload.allowedTypes">image/gif,image/jpeg
</param>
</interceptor-ref>
<result name="success">/success.jsp</result>
<result name="input">/index.jsp</result>
</action>
</package>
</struts>
2.3 index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
</head>
<body>
<s:form action="upload_test1" method="post" enctype="multipart/form-data">
<s:file name="ppt" label="pptFile"></s:file>
<s:textfield name="description" label="pptdesc"></s:textfield>
<s:submit value="上传"></s:submit>
</s:form>
</body>
</html>
注意:在进行文件的上传的时候要对form表单进行一些修改
修改1:enctype=”multipart/form-data”
修改2:method=”post”
修改3:input标签的type=”file”
2.4 success.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>文件上传成功!</title>
</head>
<body>
文件上传成功!!!<a href="index.jsp">返回</a>
</body>
</html>
2.5 工具类(本文将对文件名进行UUID以及IO操作封装成方法了)
package com.wh.utils;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.UUID;
import javax.servlet.ServletContext;
import org.apache.struts2.ServletActionContext;
public class UUID_Util {
public static void getChildDirectoryAndIO(File file,String FileName){
//获取文件名的哈希值
int hashcode = FileName.hashCode();
//将哈希值转换成字符串
String code = Integer.toHexString(hashcode);
//将文件打散,对于大文件来说可以提高文件的检索速度
String ChildDirectory = code.charAt(0)+File.separator+code.charAt(1);
ServletContext servletContext = ServletActionContext.getServletContext();
String parent = servletContext.getRealPath("/WEB-INF/files/"+ChildDirectory);
//对文件名采用UUID进行处理。防止文件的重名
String child = UUID.randomUUID().toString()+"_"+FileName;
File f = new File(parent);
if(!f.exists()){
f.mkdirs();
}
//获取缓冲区
BufferedOutputStream bos = null;
BufferedInputStream bis = null;
FileInputStream fis = null;
FileOutputStream fos = null;
try {
fis = new FileInputStream(file);
fos = new FileOutputStream(new File(parent,child));
bis = new BufferedInputStream(fis);
bos = new BufferedOutputStream(fos);
byte [] buffer = new byte[1024*2];
int len = 0;
try {
while((len=fis.read(buffer))!=-1){
fos.write(buffer, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}finally{
if(bis!=null){
try {
bis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(bos!=null){
try {
bos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(fis!=null){
try {
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(fos!=null){
try {
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
2.6 FileUploadAction.java
package com.wh.upload;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.UUID;
import javax.servlet.ServletContext;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.wh.utils.UUID_Util;
public class FileUploadAction extends ActionSupport{
/**
*
*/
private static final long serialVersionUID = 1L;
private File ppt;//file对应的文件对象
private String pptContentType;//文件类型
private String pptFileName;//文件名
private String description;
public String test1(){
String str=null;
System.out.println("ppt="+ppt);
System.out.println("pptContentType="+pptContentType);
System.out.println("pptFileName="+pptFileName);
System.out.println("description="+description);
UUID_Util.getChildDirectoryAndIO(ppt, pptFileName);
str="success";
return str;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public File getPpt() {
return ppt;
}
public void setPpt(File ppt) {
this.ppt = ppt;
}
public String getPptContentType() {
return pptContentType;
}
public void setPptContentType(String pptContentType) {
this.pptContentType = pptContentType;
}
public String getPptFileName() {
return pptFileName;
}
public void setPptFileName(String pptFileName) {
this.pptFileName = pptFileName;
}
}
控制台打印
ppt=F:\Tomcat 6.0\work\Catalina\localhost\struts2_upload\upload__3e8e5778_15be7c2e1ad__8000_00000006.tmp
pptContentType=image/gif
pptFileName=gif53_029.gif
description=上传啦!