struts上传与显示图片例子参考(一)

来源:互联网 发布:手机淘宝怎么注册用户 编辑:程序博客网 时间:2024/05/22 21:39

例一:struts中上传(图片)文件的例子

正在学习struts这个框架,目前正在利用这个框架开发一个小型的Blog Web,其中涉及到上传图片文件,所以写了个例子demo,欢迎指点。

1.上传文件的jsp文件代码:uploadfile.jsp

<%@ page contentType="text/html;charset=GBK" language="java" %>
<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>

<html>
<head>
<title>一个上传文件的例子</title>
</head>
<BODY>
<h1>一个上传文件的例子</h1>
<html:errors/><br>
<html:form action="uploadfile.do" enctype="multipart/form-data">
    <html:file property="file" /><br><br>
    <html:submit></html:submit>
</html:form>
</BODY>

</html>

2.sucess.jsp代码:

<%@ page contentType="text/html;charset=GBK" language="java" %>
<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>

<html>
<h1>上传成功...</h1><html:link forward="index">返回</html:link>
</html>

3.ActionForm类代码:UploadFileForm.java

//Created by MyEclipse Struts
// XSL source (default): platform:/plugin/com.genuitec.eclipse.cross.easystruts.eclipse_4.0.0/xslt/JavaClass.xsl

package testfile.forms;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionError;

import org.apache.struts.upload.FormFile;
import org.apache.struts.upload.MultipartRequestHandler;

/**
* MyEclipse Struts
* Creation date: 11-14-2005
*
* XDoclet definition:
* @struts.form name="uploadForm"
*/
public class UploadFileForm extends ActionForm {

private FormFile file=null;
//private String fname;
//private String size;
//private String url;

public FormFile getFile(){
    return file;
}
public void setFile(FormFile file){
    this.file=file;
}
//**************验证文件如果为空则返回*****************
public ActionErrors validate(
    ActionMapping mapping,
    HttpServletRequest request) {
  
    ActionErrors errors=new ActionErrors();
  
    if(file==null || file.getFileSize()<5 || file.getFileName()==null){
     errors.add("file",new ActionError("error.file.null"));
    }
  
    return errors;
}


public void reset(ActionMapping mapping, HttpServletRequest request) {

  
}

}

4.Action类中的代码:UploadFileAction.java

//Created by MyEclipse Struts
// XSL source (default): platform:/plugin/com.genuitec.eclipse.cross.easystruts.eclipse_4.0.0/xslt/JavaClass.xsl

package testfile.actions;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionError;
import org.apache.struts.upload.*;
import testfile.forms.*;
import java.io.*;

/**
* MyEclipse Struts
* Creation date: 11-14-2005
*
* XDoclet definition:
* @struts.action validate="true"
*/
public class UploadFileAction extends Action{


public ActionForward execute (
    ActionMapping mapping,
    ActionForm form,
    HttpServletRequest request,
    HttpServletResponse response) throws Exception{
  
    ActionErrors errors=new ActionErrors();  
  
    UploadFileForm hff=(UploadFileForm)form;  
    FormFile file=hff.getFile();
  
  
    //*************如果ActionForm中没验证则加上这段*****************
    //if(file==null || file.getFileSize()<10 || file.getFileName()==null){
    // errors.add("file",new ActionError("error.file.null"));
    // saveErrors(request,errors);
    // return (new ActionForward(mapping.getInput()));
    //}
  
          //*************取得上传文件的信息****************
    String dir=servlet.getServletContext().getRealPath("/upload");
    String fname=file.getFileName();
    String size=Integer.toString(file.getFileSize())+"bytes";
    String url=dir+"//"+fname;
  
    //*************限制非图片文件的上传*******************
    String fileType=(fname.substring(fname.lastIndexOf('.')+1)).toLowerCase();
    if((!fileType.equals("jpg")) && (!fileType.equals("bmp")) && (!fileType.equals("gif")) && (!fileType.equals("jpeg"))){
     errors.add("filetype",new ActionError("error.file.type"));
     saveErrors(request,errors);
     return (new ActionForward(mapping.getInput()));
    }
  
    //*************限制文件不能超过2M******************
    if(file.getFileSize()>2097152){
     errors.add("size",new ActionError("error.file.size"));
     saveErrors(request,errors);
     return (new ActionForward(mapping.getInput()));
    }  
   
    //*************要用到的输入输出流*****************
    InputStream streamIn=file.getInputStream();
    OutputStream streamOut=new FileOutputStream(url);
  
    //*************将文件输出到目标文件*****************
    int bytesRead=0;
    byte[] buffer=new byte[8192];
    while((bytesRead=streamIn.read(buffer,0,8192))!=-1){
     streamOut.write(buffer,0,bytesRead);
    }
  
    streamOut.close();
    streamIn.close();
    file.destroy();    
    
    return mapping.findForward("sucess");
}

}

5.properties文件内容:
error.file.size=The file is too large,the size must less than 2M !

error.file.null=Please choose the file!

error.file.type=Type of the file must be ".jpg" or ".jpeg" or ".bmp" or ".gif" !

6.struts-config.xml代码:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.1//EN" "http://jakarta.apache.org/struts/dtds/struts-config_1_1.dtd">

<struts-config>
  
    <form-beans >
      <form-bean name="uploadForm" type="testfile.forms.UploadFileForm" />

    </form-beans>
    <global-forwards>
      <forward name="sucess" path="/sucess.jsp" />
      <forward name="index" path="/uploadfile.jsp" />
    </global-forwards>
    <action-mappings >
      <action path="/uploadfile"
        name="uploadForm"
        scope="request"
        input="/uploadfile.jsp"
        type="testfile.actions.UploadFileAction" />

    </action-mappings>

    <message-resources parameter="com.yourcompany.struts.ApplicationResources" />
</struts-config>

7.web.xml代码:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>
    <servlet>
      <servlet-name>action</servlet-name>
      <servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
      <init-param>
        <param-name>config</param-name>
        <param-value>/WEB-INF/struts-config.xml</param-value>
      </init-param>
      <init-param>
        <param-name>debug</param-name>
        <param-value>3</param-value>
      </init-param>
      <init-param>
        <param-name>detail</param-name>
        <param-value>3</param-value>
      </init-param>
      <load-on-startup>0</load-on-startup>
    </servlet>
  
    <servlet-mapping>
      <servlet-name>action</servlet-name>
      <url-pattern>*.do</url-pattern>
    </servlet-mapping>
  
    <welcome-file-list>
     <welcome-file>uploadfile.jsp</welcome-file>
    </welcome-file-list>
  
    <taglib>
     <taglib-uri>/WEB-INF/struts-html.tld</taglib-uri>
     <taglib-location>/WEB-INF/struts-html.tld</taglib-location>
    </taglib>
</web-app>

 

完毕。

例二:java+mysql中保存图片及显示上传的图片struts+hibernate
用Java做了一下在Mysql中上传及显示图片的测试,struts+hibernate
jsp页面
<html:form action="/department.do?method=AddImage" enctype="multipart/form-data">
<table>
<tr>
<td>姓名</td>
<td>
<html:text property="name"></html:text>

</tr>
<tr>
<td>电话</td>
<td><html:text property="tel"></html:text></td>
</tr>
<tr><td>
<html:file property="image"></html:file>
</td></tr>
<tr><td colspan="2"><html:submit></html:submit></td></tr>
</table>
</html:form>

actionForm代码
public class DepartmentForm extends ActionForm {
/*
* Generated fields
*/

/** tel property */
private String tel;

/** name property */
private String name;
private String id;
private FormFile image;
/*
* Generated Methods
*/

public String getId() {
return id;
}

public void setId(String id) {
this.id = id;
}

 

/**
* Method validate
* @param mapping
* @param request
* @return ActionErrors
*/
public ActionErrors validate(ActionMapping mapping,
HttpServletRequest request) {
// TODO Auto-generated method stub
return null;
}

/**
* Method reset
* @param mapping
* @param request
* @throws UnsupportedEncodingException
*/
public void reset(ActionMapping mapping, HttpServletRequest request)

{
// TODO Auto-generated method stub
try
{
request.setCharacterEncoding("gb2312");
}
catch(Exception ex)
{

}
}

/**
* Returns the tel.
* @return String
*/
public String getTel() {
return tel;
}

/**
* Set the tel.
* @param tel The tel to set
*/
public void setTel(String tel) {
this.tel = tel;
}

/**
* Returns the name.
* @return String
*/
public String getName() {
return name;
}

/**
* Set the name.
* @param name The name to set
*/
public void setName(String name) {
this.name = name;
}

public FormFile getImage() {
return image;
}

public void setImage(FormFile image) {
this.image = image;
}
}

action中代码
public ActionForward AddImage(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
{
try
{

//保存图片信息
DepartmentForm departmentform = (DepartmentForm)form;
Department department = new Department();
InputStream inputStream = departmentform.getImage().getInputStream();
department.setName(departmentform.getName());
department.setTel(departmentform.getTel());
department.setImage(Hibernate.createBlob(inputStream));
DepartmentDAO departmentDao = new DepartmentDAO();
departmentDao.save(department);

//显示图片
Department department2 = (Department)departmentDao.findByProperty("id", department.getId()).get(0);
Blob imageblob = (Blob)department2.getImage() ;
InputStream input = imageblob.getBinaryStream();
byte [] image = new byte[input.available()];
ServletOutputStream out = response.getOutputStream();
int len = 0;
while((len=input.read(image))!=-1)
{
out.write(image,0,len);
}
out.flush();
out.close();
return null;
}
catch(Exception ex)
{
return null ;
}
}




例三:struts+hibernate显示图片示例


ImageShowAction.java是用于显示图片的Action,这个action先把数据库里的图片取出,用blob类型的变量存起来,然后转化成InputStream的二进制流,再存储到byte[]数组,最后在response对象里设置图片格式,用OutPutStream输出就OK啦。下面是示例代码:
Session session = HibernateUtil.currentSession(); //获得Hibernate的全局控制对象session
          Cloth cloth = (Cloth) session.load(Cloth.class,new Integer(1));
          Blob img = cloth.getImage();
          InputStream is = img.getBinaryStream();
          int length = 0;
          try {
              length = is.available();
          } catch (IOException e) {
              e.printStackTrace();
          }
          byte[] buf = new byte[length];
          try {
              is.read(buf);
          } catch (IOException e) {
              e.printStackTrace();
          }
          response.setContentType("image/jpeg");
          OutputStream toClient = null;
          try {
              toClient = response.getOutputStream();
              toClient.write(buf);      //得到向客户端输出二进制数据的对象
              toClient.close();      //输出数据
          }catch (IOException e) {
              e.printStackTrace();
          }
JSP页面用下面的代码即可调用此action显示出图片
<img src="/showimage.do">
其中showimage.do在struts-config.xml中配置定义为ImageShowAction.java

例四:使用struts的upload组件

使用struts的upload组件。

在jsp中写入以下的基于struts tag的表单;
<html:form action="/upload" enctype="multipart/form-data" >
请选择你要上传的文件:<BR>
<html:file property="theFile" />
</html:form>

你要写一个ActionForm以和这个表单联系。
ActionForm中必须有一个FormFile类实例,
实例名和页面中的<html:file property="theFile" />中的属性名一致,即也是theFile:
例如:

public MyFileForm extends ActionForm{


FormFile theFile; //需要import org.apache.struts.upload.FormFile;


}

这样在你的上传表单提交时,struts实际上已经将你要上传的文件,变成了包含有文件流的FormFile类;

你就可以用这个FileInputStream流写在服务器所在的计算机上的任何地方了。

在Action类中你需要这样写:

InputStream ins = theFile.getInputStream();

得到这个流就好办多了:

OutputStream bos = new FileOutputStream(theForm.getFilePath());
int bytesRead = 0;
byte[] buffer = new byte[8192];
while ((bytesRead = stream.read(buffer, 0, 8192)) != -1) {
bos.write(buffer, 0, bytesRead);
}
bos.close();

例一:struts中上传(图片)文件的例子

正在学习struts这个框架,目前正在利用这个框架开发一个小型的Blog Web,其中涉及到上传图片文件,所以写了个例子demo,欢迎指点。

1.上传文件的jsp文件代码:uploadfile.jsp

<%@ page contentType="text/html;charset=GBK" language="java" %>
<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>

<html>
<head>
<title>一个上传文件的例子</title>
</head>
<BODY>
<h1>一个上传文件的例子</h1>
<html:errors/><br>
<html:form action="uploadfile.do" enctype="multipart/form-data">
    <html:file property="file" /><br><br>
    <html:submit></html:submit>
</html:form>
</BODY>

</html>

2.sucess.jsp代码:

<%@ page contentType="text/html;charset=GBK" language="java" %>
<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>

<html>
<h1>上传成功...</h1><html:link forward="index">返回</html:link>
</html>

3.ActionForm类代码:UploadFileForm.java

//Created by MyEclipse Struts
// XSL source (default): platform:/plugin/com.genuitec.eclipse.cross.easystruts.eclipse_4.0.0/xslt/JavaClass.xsl

package testfile.forms;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionError;

import org.apache.struts.upload.FormFile;
import org.apache.struts.upload.MultipartRequestHandler;

/**
* MyEclipse Struts
* Creation date: 11-14-2005
*
* XDoclet definition:
* @struts.form name="uploadForm"
*/
public class UploadFileForm extends ActionForm {

private FormFile file=null;
//private String fname;
//private String size;
//private String url;

public FormFile getFile(){
    return file;
}
public void setFile(FormFile file){
    this.file=file;
}
//**************验证文件如果为空则返回*****************
public ActionErrors validate(
    ActionMapping mapping,
    HttpServletRequest request) {
  
    ActionErrors errors=new ActionErrors();
  
    if(file==null || file.getFileSize()<5 || file.getFileName()==null){
     errors.add("file",new ActionError("error.file.null"));
    }
  
    return errors;
}


public void reset(ActionMapping mapping, HttpServletRequest request) {

  
}

}

4.Action类中的代码:UploadFileAction.java

//Created by MyEclipse Struts
// XSL source (default): platform:/plugin/com.genuitec.eclipse.cross.easystruts.eclipse_4.0.0/xslt/JavaClass.xsl

package testfile.actions;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionError;
import org.apache.struts.upload.*;
import testfile.forms.*;
import java.io.*;

/**
* MyEclipse Struts
* Creation date: 11-14-2005
*
* XDoclet definition:
* @struts.action validate="true"
*/
public class UploadFileAction extends Action{


public ActionForward execute (
    ActionMapping mapping,
    ActionForm form,
    HttpServletRequest request,
    HttpServletResponse response) throws Exception{
  
    ActionErrors errors=new ActionErrors();  
  
    UploadFileForm hff=(UploadFileForm)form;  
    FormFile file=hff.getFile();
  
  
    //*************如果ActionForm中没验证则加上这段*****************
    //if(file==null || file.getFileSize()<10 || file.getFileName()==null){
    // errors.add("file",new ActionError("error.file.null"));
    // saveErrors(request,errors);
    // return (new ActionForward(mapping.getInput()));
    //}
  
          //*************取得上传文件的信息****************
    String dir=servlet.getServletContext().getRealPath("/upload");
    String fname=file.getFileName();
    String size=Integer.toString(file.getFileSize())+"bytes";
    String url=dir+"//"+fname;
  
    //*************限制非图片文件的上传*******************
    String fileType=(fname.substring(fname.lastIndexOf('.')+1)).toLowerCase();
    if((!fileType.equals("jpg")) && (!fileType.equals("bmp")) && (!fileType.equals("gif")) && (!fileType.equals("jpeg"))){
     errors.add("filetype",new ActionError("error.file.type"));
     saveErrors(request,errors);
     return (new ActionForward(mapping.getInput()));
    }
  
    //*************限制文件不能超过2M******************
    if(file.getFileSize()>2097152){
     errors.add("size",new ActionError("error.file.size"));
     saveErrors(request,errors);
     return (new ActionForward(mapping.getInput()));
    }  
   
    //*************要用到的输入输出流*****************
    InputStream streamIn=file.getInputStream();
    OutputStream streamOut=new FileOutputStream(url);
  
    //*************将文件输出到目标文件*****************
    int bytesRead=0;
    byte[] buffer=new byte[8192];
    while((bytesRead=streamIn.read(buffer,0,8192))!=-1){
     streamOut.write(buffer,0,bytesRead);
    }
  
    streamOut.close();
    streamIn.close();
    file.destroy();    
    
    return mapping.findForward("sucess");
}

}

5.properties文件内容:
error.file.size=The file is too large,the size must less than 2M !

error.file.null=Please choose the file!

error.file.type=Type of the file must be ".jpg" or ".jpeg" or ".bmp" or ".gif" !

6.struts-config.xml代码:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.1//EN" "http://jakarta.apache.org/struts/dtds/struts-config_1_1.dtd">

<struts-config>
  
    <form-beans >
      <form-bean name="uploadForm" type="testfile.forms.UploadFileForm" />

    </form-beans>
    <global-forwards>
      <forward name="sucess" path="/sucess.jsp" />
      <forward name="index" path="/uploadfile.jsp" />
    </global-forwards>
    <action-mappings >
      <action path="/uploadfile"
        name="uploadForm"
        scope="request"
        input="/uploadfile.jsp"
        type="testfile.actions.UploadFileAction" />

    </action-mappings>

    <message-resources parameter="com.yourcompany.struts.ApplicationResources" />
</struts-config>

7.web.xml代码:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>
    <servlet>
      <servlet-name>action</servlet-name>
      <servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
      <init-param>
        <param-name>config</param-name>
        <param-value>/WEB-INF/struts-config.xml</param-value>
      </init-param>
      <init-param>
        <param-name>debug</param-name>
        <param-value>3</param-value>
      </init-param>
      <init-param>
        <param-name>detail</param-name>
        <param-value>3</param-value>
      </init-param>
      <load-on-startup>0</load-on-startup>
    </servlet>
  
    <servlet-mapping>
      <servlet-name>action</servlet-name>
      <url-pattern>*.do</url-pattern>
    </servlet-mapping>
  
    <welcome-file-list>
     <welcome-file>uploadfile.jsp</welcome-file>
    </welcome-file-list>
  
    <taglib>
     <taglib-uri>/WEB-INF/struts-html.tld</taglib-uri>
     <taglib-location>/WEB-INF/struts-html.tld</taglib-location>
    </taglib>
</web-app>

 

完毕。

例二:java+mysql中保存图片及显示上传的图片struts+hibernate
用Java做了一下在Mysql中上传及显示图片的测试,struts+hibernate
jsp页面
<html:form action="/department.do?method=AddImage" enctype="multipart/form-data">
<table>
<tr>
<td>姓名</td>
<td>
<html:text property="name"></html:text>

</tr>
<tr>
<td>电话</td>
<td><html:text property="tel"></html:text></td>
</tr>
<tr><td>
<html:file property="image"></html:file>
</td></tr>
<tr><td colspan="2"><html:submit></html:submit></td></tr>
</table>
</html:form>

actionForm代码
public class DepartmentForm extends ActionForm {
/*
* Generated fields
*/

/** tel property */
private String tel;

/** name property */
private String name;
private String id;
private FormFile image;
/*
* Generated Methods
*/

public String getId() {
return id;
}

public void setId(String id) {
this.id = id;
}

 

/**
* Method validate
* @param mapping
* @param request
* @return ActionErrors
*/
public ActionErrors validate(ActionMapping mapping,
HttpServletRequest request) {
// TODO Auto-generated method stub
return null;
}

/**
* Method reset
* @param mapping
* @param request
* @throws UnsupportedEncodingException
*/
public void reset(ActionMapping mapping, HttpServletRequest request)

{
// TODO Auto-generated method stub
try
{
request.setCharacterEncoding("gb2312");
}
catch(Exception ex)
{

}
}

/**
* Returns the tel.
* @return String
*/
public String getTel() {
return tel;
}

/**
* Set the tel.
* @param tel The tel to set
*/
public void setTel(String tel) {
this.tel = tel;
}

/**
* Returns the name.
* @return String
*/
public String getName() {
return name;
}

/**
* Set the name.
* @param name The name to set
*/
public void setName(String name) {
this.name = name;
}

public FormFile getImage() {
return image;
}

public void setImage(FormFile image) {
this.image = image;
}
}

action中代码
public ActionForward AddImage(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
{
try
{

//保存图片信息
DepartmentForm departmentform = (DepartmentForm)form;
Department department = new Department();
InputStream inputStream = departmentform.getImage().getInputStream();
department.setName(departmentform.getName());
department.setTel(departmentform.getTel());
department.setImage(Hibernate.createBlob(inputStream));
DepartmentDAO departmentDao = new DepartmentDAO();
departmentDao.save(department);

//显示图片
Department department2 = (Department)departmentDao.findByProperty("id", department.getId()).get(0);
Blob imageblob = (Blob)department2.getImage() ;
InputStream input = imageblob.getBinaryStream();
byte [] image = new byte[input.available()];
ServletOutputStream out = response.getOutputStream();
int len = 0;
while((len=input.read(image))!=-1)
{
out.write(image,0,len);
}
out.flush();
out.close();
return null;
}
catch(Exception ex)
{
return null ;
}
}




例三:struts+hibernate显示图片示例


ImageShowAction.java是用于显示图片的Action,这个action先把数据库里的图片取出,用blob类型的变量存起来,然后转化成InputStream的二进制流,再存储到byte[]数组,最后在response对象里设置图片格式,用OutPutStream输出就OK啦。下面是示例代码:
Session session = HibernateUtil.currentSession(); //获得Hibernate的全局控制对象session
          Cloth cloth = (Cloth) session.load(Cloth.class,new Integer(1));
          Blob img = cloth.getImage();
          InputStream is = img.getBinaryStream();
          int length = 0;
          try {
              length = is.available();
          } catch (IOException e) {
              e.printStackTrace();
          }
          byte[] buf = new byte[length];
          try {
              is.read(buf);
          } catch (IOException e) {
              e.printStackTrace();
          }
          response.setContentType("image/jpeg");
          OutputStream toClient = null;
          try {
              toClient = response.getOutputStream();
              toClient.write(buf);      //得到向客户端输出二进制数据的对象
              toClient.close();      //输出数据
          }catch (IOException e) {
              e.printStackTrace();
          }
JSP页面用下面的代码即可调用此action显示出图片
<img src="/showimage.do">
其中showimage.do在struts-config.xml中配置定义为ImageShowAction.java

例四:使用struts的upload组件

使用struts的upload组件。

在jsp中写入以下的基于struts tag的表单;
<html:form action="/upload" enctype="multipart/form-data" >
请选择你要上传的文件:<BR>
<html:file property="theFile" />
</html:form>

你要写一个ActionForm以和这个表单联系。
ActionForm中必须有一个FormFile类实例,
实例名和页面中的<html:file property="theFile" />中的属性名一致,即也是theFile:
例如:

public MyFileForm extends ActionForm{


FormFile theFile; //需要import org.apache.struts.upload.FormFile;


}

这样在你的上传表单提交时,struts实际上已经将你要上传的文件,变成了包含有文件流的FormFile类;

你就可以用这个FileInputStream流写在服务器所在的计算机上的任何地方了。

在Action类中你需要这样写:

InputStream ins = theFile.getInputStream();

得到这个流就好办多了:

OutputStream bos = new FileOutputStream(theForm.getFilePath());
int bytesRead = 0;
byte[] buffer = new byte[8192];
while ((bytesRead = stream.read(buffer, 0, 8192)) != -1) {
bos.write(buffer, 0, bytesRead);
}
bos.close();

 
原创粉丝点击