用strus2写简单的文件上传

今天给大家讲一下struts2的简单文件上传的代码

一、需要准备两个java文件上传的jar包,和struts2运行所需要的jar包

二、需要在表单《form》中必须要加入一句enctype =“multipart/form-data”,

表单enctype属性

application/x-www-form-urlencoded: 默认值,只要是能输出网页的服务器端环境都可以

multipart/form-data: 上传二进制数据,只有使用multipart/form-data ,才能完整的传递文件数据,进行上传操作

三、准备开始写这个文件上传的代码了,我们首先写单个文件上传

     (1)单文件上传

                第一步,写单个文件上传的jsp,我的是fileupload.jsp

         

<form action="upload" method="post" enctype="multipart/form-data">
        文件<input type="file" name="ppt"> <input type="submit"
            value="提交">

    </form>

<s:actionerror/>
    <s:form action="upload1" method="post" enctype="multipart/form-data">
            <s:file name="myFile" label="选择上传的文件"/>
        <s:submit value="上传"/>
    </s:form>

第二步,写Action类,FileUploadAction 继承ActionSupport类

public class UploadAction extends ActionSupport

    private File myFile; //上传文件的file对象
    private String myFileName; //上传文件名
    private String myFileContentType;//上传文件的MIME类型
    private String savePath; //保存上传文件的目录,相对于web应用程序的根路径,在struts。xml文件中配置
    public File getMyFile() {
        return myFile;
    }
    public void setMyFile(File myFile) {
        this.myFile = myFile;
    }
    public String getMyFileName() {
        return myFileName;
    }
    public void setMyFileName(String myFileName) {
        this.myFileName = myFileName;
    }
    public String getMyFileContentType() {
        return myFileContentType;
    }
    public void setMyFileContentType(String myFileContentType) {
        this.myFileContentType = myFileContentType;
    }
    public String getSavePath() {
        return savePath;
    }
    public void setSavePath(String savePath) {
        this.savePath = savePath;
    }

然后写继承ActionSupport的execute()方法

第一种比较简单,直接使用FileInputStream和FileOutputStream

public String execute() throws Exception {
        
        //1.获取文件上传所需路径
        String url =ServletActionContext.getServletContext().getRealPath("/files/"+pptFileName);
        FileInputStream fis =new FileInputStream(ppt);
        
        FileOutputStream fos =new FileOutputStream(url);
        
        int len=0;
        byte [] b= new byte[1024];
        while((len=fis.read(b)) != -1) {
            fos.write(b, 0, len);     
        }
        fos.close();
        fis.close();
        return SUCCESS;
    }

第二种比较复杂,使用了BufferStream流

    public String execute() throws Exception {
        
        //得到当前时间自1970年1月1日0时0分0秒开始流逝的毫秒数,将这个毫秒作为上传文件新的文件名
        long now =new Date().getTime();
        
        //得到保存上传文件的目录的真实路径
        String path =ServletActionContext.getServletContext().getRealPath(“/files/”+myFileName);
        
        File dir =new File(path);
        
        //如果这个目录不存在,则创建它
        if(!dir.exists()) 
            dir.mkdir();
        int index =myFileName.lastIndexOf(".");
        //判断上传文件名是否有扩展名
        if(index!=-1) {
            newFileName =now+myFileName.substring(index);
        }else {
            newFileName =Long.toString(now);
        }
        BufferedOutputStream bos =null;
        BufferedInputStream bis =null;
        //读取保存在临时目录下的上传文件,写入到新的文件中
        FileInputStream fis =new FileInputStream(myFile);
        bis =new BufferedInputStream(fis);
        FileOutputStream fos =new FileOutputStream(new File(dir,myFileName));
        byte[] b =new byte[1024];
        int len=-1;
        while((len=bis.read(b))!=-1) {
            fos.write(b,0,len);
        }
        bis.close();
        fos.close();
        
        return SUCCESS;
    }
 

第三步我们开始配置struts.xml,进行导包操作

<struts>

    <package name="upLoad" extends="struts-default" namespace="/">

        <action name="upload"
            class="com.qst.struts.upload.UpLoadAction" method="execute">
            <result name="success">/success.jsp</result>
        </action>
    </package>

</struts>

最后我们就可以进行运行输出了,值得注意的是struts.xml可以定义文件下载的路径,当仅仅使用FileInputStream方式时,文件下载的路径可以直接通过  String url =ServletActionContext.getServletContext().getRealPath("/files/"+pptFileName);来确定

(2)多文件上传

先写jsp页面listupload.jsp

<form action ="listload" method ="post" enctype="multipart/form-data">
        <p>
            文件1:<input type="file" name="doc">
        </p>
        <p>
            文件2:<input type="file" name="doc"> 
        </p>
        <p>
            文件3:<input type="file" name="doc"> 
        </p>
        <p>
            <input type="submit" value="提交">
        </p>

    </form>


    <%@ taglib uri="/struts-tags" prefix="s"%>
    <s:form  action ="listload" method ="post" enctype="multipart/form-data">
    <s:file name ="doc"  label ="请上传你的文件"> </s:file>
    <s:file name ="doc" label ="请上传你的文件"> </s:file>
    <s:file name ="doc" label ="请上传你的文件"> </s:file>
    <s:submit name ="提交"></s:submit>
    </s:form>

这两种方式都可以

第二步写action类,这里提供了可以更改文件名字的方法getFilename();

package com.qst.struts.upload;

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

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

public class MuchLoadAction extends ActionSupport {
    
    //使用List封装多个上传文件域的对应的文件内容
    private List<File> doc;
    
    //使用List封装多个上传文件域对应的文件类型
    private List<String> docContentType;
    
    //使用List封装多个上传文件域对应的文件名
    private List<String> docFileName;
    
    //使用list对象封装多个上传文件域的提示
    private List<String> docDesc;
    

    public List<File> getDoc() {
        return doc;
    }

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

    public List<String> getDocContentType() {
        return docContentType;
    }

    public void setDocContentType(List<String> docContentType) {
        this.docContentType = docContentType;
    }

    public List<String> getDocFileName() {
        return docFileName;
    }

    public void setDocFileName(List<String> docFileName) {
        this.docFileName = docFileName;
    }
    

    
    public List<String> getDocDesc() {
        return docDesc;
    }

    public void setDocDesc(List<String> docDesc) {
        this.docDesc = docDesc;
    }
    
    public String getPath() {
        return ServletActionContext.getServletContext().getRealPath("/files/");
    }

    public String execute() throws Exception{
        
        
        
        for(int i=0;i<doc.size();i++) {
            docFileName.set(i, getFileName(docFileName.get(i)));
            
            FileOutputStream fos =new FileOutputStream(getPath()+docFileName.get(i));
            File file =doc.get(i);
            FileInputStream fis =new FileInputStream(file);
            byte[] b =new byte[1024];
            int len =0;
            while((len=fis.read(b))!=-1) {
                fos.write(b, 0, len);
            }
        
        }
        
        
        return SUCCESS;
        
    }
    public String getFileName(String fileName) {
        
        int position =fileName.lastIndexOf(".");
        String extension =fileName.substring(position);
        
        int random =new Random().nextInt(1000);
        
        return " "+System.currentTimeMillis()+random+extension;
    }    

}

第三步配置struts.xml

<action name="listload"
            class="com.qst.struts.upload.MuchLoadAction" method="execute">
            <result name="success">/success.jsp</result>
        </action>

最后运行即可

猜你喜欢

转载自blog.csdn.net/masterpieve/article/details/81586211