struts2文件异步上传带进度条(二)

这次写的struts2文件上传带进度条是在(一)的基础上进行的,主要是实现表单的异步提交,这样,就可以很好的交互。因为在实践中,一个表单,除了要上传的文件,还有一些其他的内容,要想让文件先上传,然后再提交表单,这就要让文件先提交,然后再提交后面的。一开始走了一些弯路,用jquery来提交文件,但发现这个时候,页面总是刷新,这个时候,就不能实现预先的功能,于是,我想到了用frameset,但这个还是不太好,太复杂了。后来,我想用两个表单来实现,文件一个表单,文件其他的内容一个表单。但最重要的是,要让文件那个表单提交的时候不要刷新,这样就要用异步提交了,而且有文件的异步提交,我在网上找了很多文章,最后用jquery form js进行了实现。
![这个是文件以外内容的表单](https://img-blog.csdn.net/20150604193705806)
![这个是文件上传的表单](https://img-blog.csdn.net/20150604193740891)
<script type="text/javascript" src="${pageContext.request.contextPath }/js/jquery-1.8.2.min.js">script>
<script type="text/javascript" src="${pageContext.request.contextPath }/js/jquery.form.js">script>
要使用query的form js的插件,还得下载,下载后,然后引入,下载地址如下:http://www.vaikan.com/docs/jquery.form.plugin/jquery.form.plugin.html#sample3
然后,页面异步上传的代码如下:包含了验证的功能,验证文件是否为空,文件的上传类型,文件的大小。

struts2的配置文件如下:
<bean type="org.apache.struts2.dispatcher.multipart.MultiPartRequest" 
    name="jakarta_ex" 
    class="com.jxnu.stms.util.JakartaMultiPartRequestEx" 
    scope="default"/>
    <constant name="struts.multipart.parser" value="jakarta_ex"/>

=======================================================

        <action name="set_task" class="setTaskAction" method="set_task">
            
            <param name="savePath">/teacher/uploadparam>  
            <result name="set_task" type="chain">task_listresult>
            <result name="input">set_task.jspresult>
        action>

        <action name="set_file" class="setTaskAction" method="set_file">
            <param name="savePath">/teacher/uploadparam>  
            <result name="set_file" type="json">
                <param name="root">taskfileFileNameparam>
            result>
            <result name="input">set_task.jspresult>
        action>


        
        <action name="upload_delete" class="setTaskAction" method="delete">
        <param name="savePath">/teacher/uploadparam>
            <result name="delete" type="json">
            <param name="root">resultparam>
            result>
        action>


        
        <action name="upload_process" class="fileUploadProgressAction" method="upload_process">
            <result type="json">
                <param name="root">percentparam>
            result>
        action>
在这里,我把原来文件上传的过滤去除了,直接是在客户端进行处理

Java代码如下:

@Controller
@Scope("prototype")
public class SetTaskAction extends ActionSupport implements ModelDriven,SessionAware{
    private static final long serialVersionUID = 1584704723117564063L;
    private Task task = new Task();
    @Override
    public Task getModel() {
        return task;
    }
    private int tnum;
    private int cnum;

    public int getTnum() {
        return tnum;
    }
    public void setTnum(int tnum) {
        this.tnum = tnum;
    }
    public int getCnum() {
        return cnum;
    }
    public void setCnum(int cnum) {
        this.cnum = cnum;
    }
    private File taskfile;
    private String taskfileFileName;
    private String taskfileContentType;

    public File getTaskfile() {
        return taskfile;
    }
    public void setTaskfile(File taskfile) {
        this.taskfile = taskfile;
    }
    public String getTaskfileFileName() {
        return taskfileFileName;
    }
    public void setTaskfileFileName(String taskfileFileName) {
        this.taskfileFileName = taskfileFileName;
    }
    public String getTaskfileContentType() {
        return taskfileContentType;
    }
    public void setTaskfileContentType(String taskfileContentType) {
        this.taskfileContentType = taskfileContentType;
    }
    public static long getSerialversionuid() {
        return serialVersionUID;
    }

    private TeacherService teacherService;


    public TeacherService getTeacherService() {
        return teacherService;
    }
    @Resource
    public void setTeacherService(TeacherService teacherService) {
        this.teacherService = teacherService;
    }
    private String savePath;
    public String getSavePath() {
        return savePath;
    }
    public void setSavePath(String savePath) {
        this.savePath = savePath;
    }
    private Map session;
    @Override
    public void setSession(Map session) {
        this.session=session;

    }
    private String result;

    public String getResult() {
        return result;
    }
    public void setResult(String result) {
        this.result = result;
    }
    public String set_task() throws IOException{
        Course c = new Course();
        c.setCnum(cnum);
        Teacher t = new Teacher();
        t.setTnum(tnum);
        task.setTaskPath(taskfileFileName);
        task.setCourse(c);
        task.setTeacher(t);
        teacherService.setTask(task);

        return "set_task";
    }
    public String set_file() throws IOException{
        String dstPath=ServletActionContext.getServletContext().getRealPath(this.getSavePath()+"/"+tnum+taskfileFileName);
        File dstFile = new File(dstPath);
        FileUpload f=new FileUpload();
        f.copy(taskfile,dstFile);
        session.put("taskfileFileName", taskfileFileName);
        return "set_file";
    }

    public String delete(){
        String path=ServletActionContext.getServletContext().getRealPath(this.getSavePath()+"/"+tnum+taskfileFileName);
        new File(path).delete();
        result="成功";
        return "delete";
    }
}

文件上传的进度获取的action:

@Controller
@Scope("prototype")
public class FileUploadProgressAction extends ActionSupport implements SessionAware{

    private static final long serialVersionUID = 7345654599038757564L;
    private Map session;
    private int percent;

    public int getPercent() {
        return percent;
    }

    public void setPercent(int percent) {
        this.percent = percent;
    }

    public Map getSession() {
        return session;
    }

    @Override
    public void setSession(Map session) {
        this.session=session;

    }

    public String upload_process() throws Exception {
        percent=(int) session.get("pre");
        System.out.println(percent);
        return SUCCESS;
    }
}

action中的copy方法,即文件的处理:从拷贝到服务器的某个位置

package com.jxnu.stms.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class FileUpload {

    private static final int BUFFER_SIZE = 16*1024;

    public void copy(File src, File dst) throws IOException {
        InputStream in = null;
        OutputStream out = null;

        in = new BufferedInputStream(new FileInputStream(src),BUFFER_SIZE);
        out = new BufferedOutputStream(new FileOutputStream(dst),BUFFER_SIZE);
        byte[] buffer = new byte[BUFFER_SIZE];
        int len=0;
        while((len=in.read(buffer))>0){

                out.write(buffer, 0, len);
        }

            {
                if(null!= in){

                        in.close();

                }
                if(null != out){

                        out.close();

                }
            }
        }

}

自己覆盖的监听的方法:

package com.jxnu.stms.util;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.ProgressListener;

public class FileUploadProgress implements ProgressListener{
    @SuppressWarnings("unused")
    private HttpServletRequest servletRequest;
    HttpSession session ;

    public FileUploadProgress(HttpServletRequest servletRequest){
        super();
        this.servletRequest = servletRequest;
        session = servletRequest.getSession();
    }


    /**
     * Updates the listeners status information.
     *
     * @param pBytesRead The total number of bytes, which have been read
     *   so far.
     * @param pContentLength The total number of bytes, which are being
     *   read. May be -1, if this number is unknown.
     * @param pItems The number of the field, which is currently being
     *   read. (0 = no item so far, 1 = first item is being read, ...)
     */
    public void update(long pBytesRead, long pContentLength, int pItems){
        int pre=0;
        if(pContentLength>-1){
        int current=(int) (pBytesRead*100/pContentLength);
        if(current>pre){
            pre=current;

            session.setAttribute("pre", pre);

        }
        }

}




}

覆盖原来struts2对文件上传的处理:

package com.jxnu.stms.util;

import java.util.List;

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;
import org.apache.struts2.dispatcher.multipart.JakartaMultiPartRequest;

public class JakartaMultiPartRequestEx extends JakartaMultiPartRequest {

    @Override
    protected List parseRequest(HttpServletRequest servletRequest,
            String saveDir) throws FileUploadException {
        DiskFileItemFactory fac = createDiskFileItemFactory(saveDir);
        ServletFileUpload upload = createServletFileUpload(fac);
        upload.setProgressListener(new FileUploadProgress(servletRequest));
        return upload.parseRequest(createRequestContext(servletRequest));
    }


}

效果如下图:struts2文件异步上传带进度条(二)_第1张图片

你可能感兴趣的:(struts2,上传,进度条,异步,进度条,struts2上传)