webwork中文件上传实现

AI权益加码!Claude Code、Cursor等20+工具免费用! 购周边限时加赠Coding Plan Lite,畅享主流AI工具!学习进阶更高效! 阅读详情

 [简单介绍]

webwork 文件上传采用拦截器的方式,叫fileUpload 

可供选择的上传组件有pell(2.1.7默认)jakata(2.2及以后默认),cos

[例子]

[注意事项]

1、cos和pell文件上传解析器不在被积极维护,会被很快移除.我们强烈建议你使用Jakarta的文件上传解析器,也就是缺省的解析器

2、处理multipartRequest pell支持中文属性和中文文件名,如果遇到中文乱码问题,建议使用pell

 

step1:
页面定义如下
    <form action="upload.do" enctype="multipart/form-data" method="post">
            <input type="file" name="doc"/>
             ......................... 省略
   </form>

step2
    action 如下
    public class UploadAction extends ActionSupport {
          .....................................
          private File doc;//doc与页面取一样的名字

          public void setDoc(File doc) {
                 this.doc = doc;
         }

         //当然还可以使用以下的咚咚
  /*
     * public void setDocContentType(String docContentType) {
     * this.docContentType = docContentType; }
     *
     *//**
         *
         * @author weip
         * @time 0:23:24 2006-5-11
         * @param docFileName
         */
    /*
     * public void setDocFileName(String docFileName) { this.docFileName =
     * docFileName; }
     */

    /**
     *
     */
    /*
     * private String docContentType;
     *
     *//**
         *
         */
    /*
     * private String docFileName;
     */

.............................................................

   }

当程序进入到action当中时,你可以开始处理上面代码中的doc,此时文件已上传到服务器中的一个临时目录(同时被注入到action中就是你看到的doc),此临时目录由webwork.properties指定,你必须将此文件拷贝到你需要的目录,否则action执行完毕,此文件会被删除,准确说是拦截器的后处理删除了临时文件,这一段结论的前提是你使用拦截器处理上传

step3
处理配置文件,配置拦截器

<action name="upload" class="com.mofile.baby.web.action.signup.UploadAction">
          
            <result name="success" type="freemarker">/page/signup/uploadfile.htm</result>
            <interceptor-ref name="fileUpload"/>
            <interceptor-ref name="defaultWebStack"/>
         
  </action>

step4
对于webwork.properties的一些处理
webwork in action上推荐使用webwork.multipart.parser=jakarta而不是默认的 pell,如果使用前者,不要忘了在你的lib中加入commons-fileupload.jar


需要注意的问题:
你在使用
fileUpload传拦截器的时候应该避免使用execAndWait拦截器,否则很有可能会出现空指针,因为execAndWait拦截器会在另一个线程处理action,而原来的线程会删掉临时文件,所以当你在action中处理文件的时候很有可能文件已被删掉,虽然这并非一定会出现,但毕竟不安全
 转自:http://blog.csdn.net/pwlazy/archive/2006/05/11/724735.aspx

 

 

方法二、(有多文档上传那块)

 用webwork框架做upload的java读取代码
    我的语言表达能力不是很好,说也许说不明白,可能给看的说得糊涂了,同样
这个对做上传得新手很有用,不啰嗦了,先写代码吧:一共4个地方要弄,
前台,后台,xwork和webwork.properties
前台:
upload.jsp:
=================================================================
<%--
  Created by IntelliJ IDEA.
  User: lvjiachun
  Date: 2006-5-3
  Time: 9:32:35
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=utf-8" language="java" %>
<%@ taglib prefix="ww" uri="/webwork" %>
<html>
<head><title>upload</title></head>
<body><p align="center">
    <ww:form action="upload.action" name="upload" method="post" enctype="multipart/form-data">
        <ww:file name="file1" value="浏览" label="ReadFile"/>
        <ww:file name="file2" value="浏览" label="ReadFile"/>
        <ww:file name="file3" value="浏览" label="ReadFile"/>
        <ww:file name="file4" value="浏览" label="ReadFile"/>
        <ww:textfield name="model.fileURL" label="Road"/>  //指定上传得文件保存到哪里
        <ww:submit/>
    </ww:form></p>
</body>
</html>
=======================================================================
upload-success.jsp
=======================================================================
<%--
  Created by IntelliJ IDEA.
  User: lvjiachun
  Date: 2006-5-3
  Time: 9:38:04
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=utf-8" language="java" %>
<%@ taglib prefix="ww" uri="/webwork" %>
<html>
<head><title>upload-success</title></head>

<body>
<p align="center">
    你已经上传成功,
    <a href="upload.jsp">请返回</a>
</p>
</body>
</html>
========================================================================
后台:一共需要三个4个java文件
1.  <FileMes>
package upload.until;

/**
 * Created by IntelliJ IDEA.
 * User: lvjiachun
 * Date: 2006-5-3
 * Time: 7:51:11
 * To change this template use File | Settings | File Templates.
 */
public class FileMes {
    private String fileName;

    public String getFileName() {
        return fileName;
    }

    public void setFileName(String fileName) {
        this.fileName = fileName;
    }

    public String getFilePath() {
        return filePath;
    }

    public void setFilePath(String filePath) {
        this.filePath = filePath;
    }

    private String filePath;
}
2.<FileSelect >
package upload.until;

/**
 * Created by IntelliJ IDEA.
 * User: lvjiachun
 * Date: 2006-5-3
 * Time: 7:51:23
 * To change this template use File | Settings | File Templates.
 */
public class FileSelect {
    private String fileName;
    private String fileURL;
    private String type;

    public String getFileName() {
        return fileName;
    }

    public void setFileName(String fileName) {
        this.fileName = fileName;
    }

    public String getFileURL() {
        return fileURL;
    }

    public void setFileURL(String fileURL) {
        this.fileURL = fileURL;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }
}
3.<UploadUntil >
package upload.until;

import com.opensymphony.webwork.dispatcher.multipart.MultiPartRequestWrapper;
import com.opensymphony.webwork.dispatcher.multipart.MultiPartRequest;
import com.opensymphony.webwork.ServletActionContext;

import java.util.List;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Calendar;
import java.io.*;

/**
 * Created by IntelliJ IDEA.
 * User: lvjiachun
 * Date: 2006-5-3
 * Time: 7:51:00
 * To change this template use File | Settings | File Templates.
 */
public class UploadUntil {
    public static List<FileMes> Upload(String smallPath) throws IOException {
        List<FileMes> fileMesList = new ArrayList<FileMes>();
        String path = smallPath;
        System.out.println("PATH 2:" + path);
        MultiPartRequestWrapper multiWrapper = (MultiPartRequestWrapper) ServletActionContext.getRequest();
        if (multiWrapper == null) return null;
        Enumeration e = multiWrapper.getFileNames();
        int i = 0;
//===============================================================//
        //这个是单文件上传的代码;!!如果想做单文件上传,把注释掉的代码去掉就可以了
//        while (e.hasMoreElements()) {
//            String inputValue = (String) e.nextElement();
//            String contentType = multiWrapper.getContentType(inputValue);
//            String flie1 = multiWrapper.getFilesystemName(inputValue);
//            String fileName = flie1;
//            System.out.println("FileName underfinded:" + fileName);
//            String savePath = path + fileName;
//            File file = multiWrapper.getFile(inputValue);
//            if (file != null) {
//                InputStream inStream = new FileInputStream(file.getPath());
//                FileMes fm = new FileMes();
//                fm.setFileName(flie1);
//                System.out.println("FileName:" + fm.getFileName());
//                System.out.println("SmallPath in UploadUntil.java" + smallPath);
//                fm.setFilePath(smallPath + fileName);
//                System.out.println("FilePath:" + fm.getFilePath());
//                fileMesList.add(fm);
//                System.out.println("SavePath:" + savePath);
//                FileOutputStream fs = new FileOutputStream(savePath);
//                byte[]buffer = new byte[1444];
//                int length;
//                int bytesum = 0;
//                int byteread = 0;
//                while ((byteread = inStream.read(buffer)) != -1) {
//                    bytesum += byteread;
//                    fs.write(buffer, 0, byteread);
//                }
//============================================================//
// 下面这个是多文件上传-------------------
        while (e.hasMoreElements()) {
            String inputValue = (String) e.nextElement();
            String contentType = multiWrapper.getContentType(inputValue);
            String flie1 = multiWrapper.getFilesystemName(inputValue);
            String fileName = Calendar.getInstance().getTime().getTime() + "-" + i + flie1;
            String savePath = path + fileName;
            File file = multiWrapper.getFile(inputValue);
            if (file != null) {
                InputStream inStream = new FileInputStream(file.getPath()); //读入原文件
                FileMes fm = new FileMes();
                fm.setFileName(flie1);
                fm.setFilePath(smallPath + fileName);
                fileMesList.add(fm);
                FileOutputStream fs = new FileOutputStream(savePath);
                byte[] buffer = new byte[1444];
                int length;
                int bytesum = 0;
                int byteread = 0;
                while ((byteread = inStream.read(buffer)) != -1) {
                    bytesum += byteread; //字节数 文件大小
                    fs.write(buffer, 0, byteread);
                }
//==============================================================//
                inStream.close();   //关闭输入流
                i++;
                if (file.exists()) {
                    file.delete();
                }   //如果上传的文件存在则将其删除;
            }

        }
        return fileMesList;
    }
}
4.也就是最后一个,action<UploadfilesAction>
package upload.fileupload;

import com.opensymphony.xwork.ActionSupport;
import com.opensymphony.xwork.Action;
import com.opensymphony.xwork.ModelDriven;
import upload.until.FileSelect;

/**
 * Created by IntelliJ IDEA.
 * User:lvjiachun
 * Date: 2006-5-3
 * Time: 7:52:34
 * To change this template use File | Settings | File Templates.
 */
public class UploadfilesAction extends ActionSupport implements Action, ModelDriven {
    FileSelect fileMes = new FileSelect();

    public String upload() throws Exception {
        String smallPath = fileMes.getFileURL();
        System.out.println(smallPath+"xiaosao");
        java.io.File myFilePath = new java.io.File(smallPath);
        if (smallPath != null) {
            if (!myFilePath.exists()) {
                myFilePath.mkdir();
                System.out.println("*******MaKe DIR!*********");
            }
        }
        upload.until.UploadUntil.Upload(smallPath);
        return SUCCESS;

    }
    public Object getModel() {
        return fileMes;  //To change body of implemented methods use File | Settings | File Templates.
    }
}
**********************************************************************
xwork中
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE xwork PUBLIC "-//OpenSymphony Group//XWork 1.1.1//EN" "
http://www.opensymphony.com/xwork/xwork-1.1.1.dtd">
<xwork>
    <include file="webwork-default.xml"/>
    <package name="upload" extends="webwork-default">
        <interceptors>
            <interceptor name="upload" class="com.opensymphony.webwork.interceptor.FileUploadInterceptor"/>
            <interceptor-stack name="uploadStack">
                <interceptor-ref name="upload"/>
                <interceptor-ref name="defaultStack"/>
            </interceptor-stack>
        </interceptors>
        <default-interceptor-ref name="WSStack"/>
    
        <action name="upload" class="upload.fileupload.UploadfilesAction" method="upload">
            <result name="success">
                <param name="location">/upload/upload-success.jsp</param>
            </result>
            <interceptor-ref name="uploadStack"/>
            <interceptor-ref name="model-driven"/>
        </action>
    </package>
</xwork>
webwork.properties
在webwork.properties中要加上这段代码
webwork.multipart.parser=com.opensymphony.webwork.dispatcher.multipart.PellMultiPartRequest
webwork.multipart.saveDir=d://  #这个是上传文件的默认保存路径#

WebWork 2.2.7 文件上传功能实现详解及实例代码 WebWork是一个轻量级的MVC框架,它基于XWork,而XWork是Apache Struts的原始设计。WebWork 2.2.7是该框架的一个稳定版本,它提供了一个灵活的Web层组件,并且支持强大的表达语言(Expression Language,EL)和OGNL(Object-Graph Navigation Language)表达式。它采用了“拦截器栈”这一概念,为开发者提供了极大的灵活性。 阅读详情

相关推荐

Webwork 文件上传的问题

今天遇到一个webwork文件上传的问题,上传 txt 文件的时候,如果文件内容为空,则上传后的文件为null,上传不成功。试了一下,如果给txt文件写一个二进制的0x00字符,即可以上传成功,如果是上传一个没有内容的word文档,也可以成功,分析原因应该是word格式自带了很多隐藏格式数据,所以其实没有文字内容的word文档也是有东西的。这样看来,只要文件实际内容为空,即不带任何字符,上传就有问...

wlbbswl的博客 338

webwork上传文件

在开源世界中,有两套比较有影响的API可供使用,一个是POI,一个是jExcelAPI。其中功能相对POI比较弱一点。但jExcelAPI对中文支持非常好,API是纯Java的, 并不依赖Windows系统,即使运行在Linux下,它同样能够正确的处理Excel文件。另外需要说明的是,这套API对图形和图表的支持很有限,而且仅仅识别PNG格式。jxl.jar可以到[url]h...

weixin_34007020的博客 115

webwork 文件上传

这两天要做一个文件上传的功能,为了配合webwork,使用了它带的上传功能,因为对拦截器没有深入的研究,被这个功能折腾了2天才弄出来,想想实在觉得花费时间太多了,还是得抽空好好系统的学习一下它,不能每次都到用的时候再折腾,那是被它折腾。 为了这个功能,也在网上搜了很多,看到很多人也碰到了跟我同样的问题,但是都没有很详细的解决过程,自己也是在山穷水尽的时候忽然就配置对了,所以记下来,...

wlbbswl的博客 199

WebWork实现文件上传

///step3import java.io.*; import java.text.SimpleDateFormat; import java.util.Calendar; import com.opensymphony.xwork.ActionSupport; public class UploadAgent extends ActionSupport { privat

greatwh的专栏 688

深入分析java中webwork中的文件上传机制

深入分析java中webwork中的文件上传机制   点击上传按钮后,webwork的程序流如下:  step 1)进入ServletDispatcher.service public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException { ........  

溺水的鱼 - Later equals never. 975

使用Webwork 2.2.4实现文件上传

webwork.properties相关配置如下: webwork.locale=zh_CNwebwork.multipart.parser=jakartawebwork.i18n.encoding = GBK 上传页面: ...@ page language="java" contentType="text/html; charset=GB18030"    pa

我的世界我的梦 1426

WebWork之--使用fileUpload interceptor实现文件上传[基本配置+注意事项]

    使用webworkfileUpload interceptor,可以很方便的实现文件上传功能。以下为我在编写文件上传功能实现中的一些总结:一:基本配置开发环境:服务器:tomcat 5.Xwebwork版本:webwork 2.2.2另外,需要把apache下的commons FileUpload包放到你的classpath中,我的是直接放置在${app}/WEB

Mov 4248

webwork实现文件上传的功能

环境:MyEclipse版本:6.0.1 ; JDK:jdk1.5.0_10   Tomcat:tomcat-5.0.28; 配置文件 web.xml<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN""http://java.sun.com/dtd/web-app_2

进步源自交流 702

使用webwork实现的图片上传==文件上传

说真的,做开发快两年了。自己感觉自己并没有多大的进步。心里很遗憾,虽然每次领导安排的任务也几乎都能完成。但是自我感觉质量部是很高。 近期发现身边的牛人同事们个个都有在维护自己的博客。每当完成一件工作就会将自己的工作总结好发出来与大家一起分享,我也知道这样做的好处。只是一直懒不愿意去写。每次都是在工作的时候东拼西凑的把工作好不容易完成,完事以后根本不想再回头去整理这些。久了以后发现自己都看不懂...

流氓来啦 344

swfupload struts2 webwork 批量上传

以前做个项目是 用到了swfupload http://stephen830.iteye.com/blog/255583?page=3#comments 这里已经说的很清楚了 由于框架整合,spring3.0+webwork2.27+hibernate3.0 上传没有用了,吼吼 搞了我1夜才搞出头绪,被绕在代码里了,最后试试了,才发现时框架问题。 因为webwork2(structs...

大蘑菇 139
上一篇: 2007-3-5
下一篇: linux集群技术详解
秤秤biubiu
博客等级 码龄22年 156粉丝 109原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值