struts2.0实现文件上传

将下面两个jar文件加入lib
commons-fileupload.jar
commons-io.jar
jsp页面

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>简单的文件上传</title>
</head>
<body>
<!-- 为了完成文件上传,设置该表单的enctype属性为multipart/form-data。 -->
<s:form action="upload.action" method="post" enctype="multipart/form-data" theme="simple">
<s:fielderror></s:fielderror>
选择文件:<s:file name ="upload"/> <br>
选择文件:<s:file name ="upload"/> <br>
选择文件:<s:file name ="upload"/> <br>
<s:submit />
</s:form>
</body>
</html>

action

action
package org.login.actions;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import org.apache.struts2.ServletActionContext;
import org.login.page.DateFormatUtil;

import com.opensymphony.xwork2.ActionSupport;

public class UploadAction extends ActionSupport {
// 封装单个上传文件域的属性
// private File upload;
// 封装单个上传文件类型的属性
// private String uploadContentType;
// 封装单个上传文件名的属性
// private String uploadFileName;

//封装多个上传文件域的属性
private List<File> upload = new ArrayList<File>();
// 封装多个上传文件类型的属性
private List<String> uploadContentType = new ArrayList<String>();
// 封装多个上传文件名的属性
private List<String> uploadFileName = new ArrayList<String>();

//动态设置上传文件保存地址
private String savePath;

public String getSavePath() {
return ServletActionContext.getRequest().getRealPath(savePath);
}

public void setSavePath(String savePath) {
this.savePath = savePath;
}

/*
* // 上传单个文件对应文件内容的setter和getter方法
* public void setUpload(File upload) {
* this.upload = upload;
* }
* public File getUpload() {
* return (this.upload);
* }
*
* //上传单个文件的文件类型的setter和getter方法
* public void setUploadContentType(String uploadContentType) {
* this.uploadContentType = uploadContentType;
* }
* public String getUploadContentType() {
* return (this.uploadContentType);
* }
*
* // 上传单个文件的文件名的setter和getter方法
* public void setUploadFileName(String uploadFileName) {
* this.uploadFileName = uploadFileName;
* }
* public String getUploadFileName() {
* return (this.uploadFileName);
* }
*/

//上传多个文件对应文件内容的setter和getter方法
public List<File> getUpload() {
return upload;
}
public void setUpload(List<File> upload) {
this.upload = upload;
}

// 上传多个文件的文件类型setter和getter方法
public List<String> getUploadContentType() {
return uploadContentType;
}
public void setUploadContentType(List<String> uploadContentType) {
this.uploadContentType = uploadContentType;
}

// 上传多个文件的文件名的setter和getter方法
public List<String> getUploadFileName() {
return uploadFileName;
}
public void setUploadFileName(List<String> uploadFileName) {
this.uploadFileName = uploadFileName;
}

public String upload() {
//上传多个文件
List<File> files = getUpload();
// String ext ="";
FileOutputStream fos = null;
FileInputStream fis = null;
byte[] buffer = new byte[1024];
int len = 0;
Random rd = new Random();
for (int i = 0; i < files.size(); i++) {
try {
//以服务器的文件保存地址和当前时间组合文件名建立上传文件输出流
// ext =uploadFileName.get(i).substring(uploadFileName.get(i).lastIndexOf('.'));
/* fos = new FileOutputStream(getSavePath()+ File.separator+
* DateFormatUtil.getCurrentCustomFormatDateTime(DateFormatUtil.DATE_TIME_FORMAT_14) +
* String.valueOf(rd.nextInt(1000))+ext);
*/
fos = new FileOutputStream(getSavePath() + File.separator
+ uploadFileName.get(i));
// 以上传文件建立一个文件上传流
fis = new FileInputStream(files.get(i));
// 将上传文件的内容写入服务器
len = 0;
while ((len = fis.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
} catch (Exception e) {
e.printStackTrace();
}
}

/*上传单个文件
* try {
* // 以服务器的文件保存地址和原文件名建立上传文件输出流
* FileOutputStream fos = new FileOutputStream(ServletActionContext .getRequest().getRealPath("") +
* File.separator + "upload" + File.separator + getUploadFileName());
* // 以上传文件建立一个文件上传流
* FileInputStream fis = new FileInputStream(getUpload());
* // 将上传文件的内容写入服务器
* byte[] buffer = new byte[1024];
* int len = 0;
* while ((len = fis.read(buffer)) > 0) {
* fos.write(buffer, 0, len);
* }
* } catch (Exception e) {
* }
*/
return SUCCESS;
}
}

struts.xml

<action name="upload" class="UploadAction" method="upload">
<!-- 配置fileUpload的拦截器 -->
<interceptor-ref name="fileUpload">
<!-- 配置允许上传的文件类型 -->
<param name="allowedTypes">
image/bmp,image/png,image/gif,image/jpeg,image/jpg,application/msword,text/plain
</param>
<!-- 配置允许上传的文件大小 -->
<param name="maximumSize">2000000000</param>
</interceptor-ref>
<interceptor-ref name="defaultStack" />
<!-- 动态设置Action的属性值 -->
<param name="savePath">/upload</param>
<result>/upload_succ.jsp</result>
<result name="input">/upload.jsp</result>
</action>


上传成功页面

<%@ page language="java" import="java.util.*" pageEncoding="GB18030"%>
<%@taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<title>上传成功</title>
</head>
<body>
上传成功!<br>
<!-- 输出上传的表单里的文件标题属性 -->
文件标题:<s:property value=" + title"/><br>
<!-- 根据上传文件的文件名,在页面上显示上传的图片 -->
文件为:<s:property value="uploadFileName"/><br>
</body>
</html>
阅读更多

struts2.0文件上传问题

06-26

我昨天用struts2.0做了一个文件上传的程序,今天在里面加了一点东西,主要是在上传的页面和struts.xml配置文件里面加了阻止用户上传非图片,也就是过滤非图片,可是却总是报空指针错误,真是郁闷了!所以在此发帖,希望各位高手赐教!rnrnrn页面上传 FileUpload.jsprnrn<%@ page language="java" contentType="text/html;charset=UTF-8"%>rn<%@ taglib prefix="s" uri="/struts-tags"%>rnrnrn rn rn rn rn rn rnrn上传图片的action类 FileUploadAction.javarnrnpackage tutorial;rnrnimport java.io.BufferedInputStream;rnimport java.io.BufferedOutputStream;rnimport java.io.File;rnimport java.io.FileInputStream;rnimport java.io.FileOutputStream;rnimport java.io.InputStream;rnimport java.io.OutputStream;rnimport java.util.Date;rnrnimport org.apache.struts2.ServletActionContext;rnimport com.opensymphony.xwork2.ActionSupport;rnrnpublic class FileUploadAction extends ActionSupportrnrn private static final long serialVersionUID = 1L;rn private static final int BUFFER_SIZE = 16 * 1024;rnrn private File myFile;rn private String contentType;rn private String fileName;rn private String imageFileName;rn private String caption;rnrn public void setContentType(String contentType)rn rn this.contentType = contentType;rn rnrn public void setFileName(String fileName)rn rn this.fileName = fileName;rn rnrn public void setMyFile(File myFile)rn rn this.myFile = myFile;rn rnrn public void setCaption(String caption)rn rn this.caption = caption;rn rnrn public String getImageFileName()rn rn return imageFileName;rn rnrn public String getCaption()rn rn return caption;rn rnrn private static void copy(File src,File dst)rn rn tryrn rn InputStream in = null;rn OutputStream out = null;rnrn tryrn rn int = new BufferedInputStream(new FileInputStream(src),BUFFER_SIZE);rn out = new BufferedOutputStream(new FileOutputStream(dst),BUFFER_SIZE);rnrn byte[] buffer = new byte[BUFFER_SIZE];rnrn while(in.read(buffer) > 0)rn rn out.write(buffer);rn rn rn finallyrn rn if(null != in)rn rn in.close();rn rnrn if(null != out)rn rn out.close();rn rn rn rn catch(Exception ex)rn rn ex.printStackTrace();rn rn rnrn private static String getExtention(String fileName)rn rn int pos = fileName.lastIndexOf(".");rn return fileName.substring(pos);rn rnrn @Overridern public String execute()rn rn imageFileName = new Date().getTime() + getExtention(fileName);rnrn File imageFile = new File(ServletActionContext.getServletContext().getRealPath("/UploadImages") + "/" + imageFileName);rn copy(myFile,imageFile);rn return SUCCESS;rn rnrnrnstruts.properties:rn struts.multipart.saveDir = /tmprnrnstruts.xmlrnrnrnrnrnrn rn rn rn rn rn image/bmp,image/png,image/gif,image/jpegrn rn rn /FileUpload.jsprn /ShowUpload.jsprn rn rnrnrnrn显示页面:ShowUpload.jsprn<%@ page language="java" pageEncoding="UTF-8"%>rn<%@ taglib prefix="s" uri="/struts-tags" %>rnrn<%rnString path = request.getContextPath();rnString basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";rn%>rnrnrnrn rn rn rn My JSP 'ShowUpload.jsp' starting pagern rn rn rn rn rn rn rnrn rn rn rn rn "/>rn rn rn rn rnrnrnrn报错信息如下:rnrn java.lang.NullPointerExceptionrn at tutorial.FileUploadAction.getExtention(FileUploadAction.java:95)rn at tutorial.FileUploadAction.execute(FileUploadAction.java:102)rn at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)rn at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)rn at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)rn at java.lang.reflect.Method.invoke(Method.java:585)rn at com.opensymphony.xwork2.DefaultActionInvocation.invokeAction(DefaultActionInvocation.java:404)rn at com.opensymphony.xwork2.DefaultActionInvocation.invokeActionOnly(DefaultActionInvocation.java:267)rn at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:229)rn at org.apache.struts2.interceptor.FileUploadInterceptor.intercept(FileUploadInterceptor.java:207)rn at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:224)rn at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:223)rn at com.opensymphony.xwork2.util.profiling.UtilTimerStack.profile(UtilTimerStack.java:455)rn at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:221)rn at org.apache.struts2.impl.StrutsActionProxy.execute(StrutsActionProxy.java:50)rn at org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:504)rn at org.apache.struts2.dispatcher.FilterDispatcher.doFilter(FilterDispatcher.java:419)rn at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)rn at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)rn at org.apache.struts2.dispatcher.ActionContextCleanUp.doFilter(ActionContextCleanUp.java:99)rn at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)rn at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)rn at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:228)rn at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)rn at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128)rn at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:104)rn at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)rn at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:216)rn at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:844)rn at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:634)rn at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:445)rn at java.lang.Thread.run(Thread.java:595)rnrn

没有更多推荐了,返回首页