Struts2 文件上传

由于Struts 2框架对上传组件进行了封装,使得文件上传的实现更简单。

在Struts 2框架中提供对commons-fileupload组件的支持,并默认使用该组件实现文件上传,因此要两个jar文件:commons-fileupload-xxxjar,commons-io-xxxjar

例子:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib uri="/struts-tags" prefix="s"%>
<%@ page isELIgnored="false" %>
jsp:
<s:form action="towoupload" enctype="multipart/form-data" method="POST">
<s:textfield name="title" label="标题"></s:textfield>
<s:file name="upload" label="选择文件"></s:file>
<s:submit name="submit" value="上传文件"></s:submit>
</s:form>
import com.opensymphony.xwork2.ActionSupport;
import org.apache.struts2.ServletActionContext;


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

/**
 * Created by lenovo on 2017/3/9.
 */
//封装上传文件属性
private File upload;
 // 封装 上传文件类型
private String uploadContentType;
    //封装上传文件名
private String uploadFileName;
    //获取文件上传的路径
private String savePath;
public class UploadAction extends ActionSupport {
  byte[] byte=new byte[1024];
 FileInputStream fis=new FileInputStream(getUpload());
 FileOutputStreem fos=new FileOutputStreem(getSavePath()+"\"+this.getUploadFileName());
 int length=fis.read(byte);
while(length>0){
  fos.write(byte,0,length);
  length=fis.read(byte);
}
  fos.flush();
        fos.close();
        fis.close();
        return SUCCESS;
}
 //获取上传文件的保存路径
//通过读取存放目录获得保存路径
public String getSavePath() {
return ServletActionContext.getServletContext().getRealPath(savePath);
}

File类型的xxx属性:与表单中的File控件的name属性一致,用于封装File控制对应的文件内容。
String类型xxxFileName属性:该属性名称由前面的File类型属性和FileName组合而成,是固定的语法,其作用是封装File控件对应文件的文件名。
String类型的xxxContentType属性:同样由xxx属性和ContetType组合而成,是固定语法,其作用是封装File控件对应文件的文件类型。
Action:
<action name="upload" class="cn.wwy.action.UploadAction">
            <param name="savePath">/upload</param>
            <result name="success">/Login.jsp</result>
        </action>




























原文地址:https://www.cnblogs.com/xiaoyu1997/p/6530310.html