• struts 文件上传


    =================================== 实现单个文件上传 ======================================

    步骤1. 导入jar包: commons-fileupload-x.x.x.jar ; commons-io-x.x.x.jar

    步骤2: JSP页面
    <s:form action="fileup.action" method="post" enctype="multipart/form-data">
    <s:file name="upload" lable="选择文件"></s:file><br/>
    <s:submit name="submit" value="上传文件"></s:submit>
    </s:form>

    步骤3: Action页面

    package org.zm.test;

    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;

    import org.apache.struts2.ServletActionContext;
    import com.opensymphony.xwork2.ActionSupport;

    public class UpLoadAction extends ActionSupport{

    private File upload;
    private String uploadContentType; //文件类型
    private String uploadFileName; //文件名称
    private String savePath; //保存路劲
    //省略getter; setter

    public String getSavePath() {

    return ServletActionContext.getServletContext().getRealPath(savePath);
    }

    public String execute() throws Exception{

    byte[] buffer = new byte[1024];

    //读取文件
    FileInputStream fis = new FileInputStream(upload);
    //保存文件,并保存文件的位置
    FileOutputStream fos = new FileOutputStream(getSavePath() + "\" + this.getUploadFileName());

    int length = fis.read(buffer);
    while(length > 0){
    fos.write(buffer, 0 , length);
    length = fis.read(buffer);
    }

    fis.close();
    fos.flush();
    fos.close();
    return SUCCESS;

    }
    }

    提示: File类型的 xxx 属性名称和JSP上传表单页面 <s:file>的文件名相同。
    String类型的xxxFileName属性,该属性由前面File类型的属性名称和FileName组合而成。
    String类型的xxxContentType属性同上。

    String类型的savePath名称与步骤3中param的名称保存一致

    步骤3: Action.xml文件

    <!-- 文件上传 -->
    <action name="fileup" class="org.zm.test.UpLoadAction">
    <param name="savePath">/upload</param>
    <result name="success">no.jsp</result>
    </action>


    ===================================== 实现多个文件上传 ==============================

    1. JSP页面
    多个 <s:file>

    2. Action页面
    private File[] upload;
    private String[] uploadContentType;
    .....

    public String execute() throws Exception(){
    byte[] buffer = new byte[1024];

    for(int i = 0; i < upload.length; i++){
    ......
    }

    return SUCCESS;
    }

  • 相关阅读:
    flask的类视图
    flask的消息提示flash和abort
    css—left和margin-left的区别
    Git(2)—特性
    JS 基础
    css
    搭建vue环境
    Git(1)—基础
    C中 输出格式
    软件测试_对于堆栈的单元测试
  • 原文地址:https://www.cnblogs.com/Theladyflower/p/4624223.html
Copyright © 2020-2023  润新知