初学struts文件上传

struts获取上传文件名和解决中文乱码

Filter,过滤字符编码

    public void doFilter(ServletRequest request, ServletResponse response,

           FilterChain chain) throws IOException, ServletException {

       request.setCharacterEncoding("GB2312");

       chain.doFilter(request, response);

    }

Web.xml

  <filter>

      <filter-name>changeEncode</filter-name>

      <filter-class>com.study.java.utils.EncodeFilter</filter-class>

  </filter>

  <filter-mapping>

      <filter-name>changeEncode</filter-name>

      <servlet-name>action</servlet-name>

  </filter-mapping>

 

Action中得到路径 this.getServlet().getServletContext().getRealPath(“/”)

保存用struts获取的上传文件内容

//Action

       //上传文件到服务器

       FormFile file1 = userForm.getFile1();

       response.setContentType("text/html;charset=UTF-8");

       String fileName = file1.getFileName();

       byte[] content = file1.getFileData();                                                       

       InputStream contentStream = file1.getInputStream();

       String saveDir = this.getServlet().getServletContext().getRealPath("/");

       File file = new File(saveDir,fileName);

       FileOutputStream fos = new FileOutputStream(file);

       int len=0;

       byte[] buf = new byte[1024];

       while((len=contentStream.read(buf))!=-1){

           fos.write(buf,0,len);

       }

       contentStream.close();

       fos.close();

       if(true){

           return null;

       }

//Struts FormBean

public class UserForm extends ActionForm {

    private FormFile file1;    //设计不是太合理,FormFile类是依赖于Struts的,离开了Struts就不行了

    public FormFile getFile1() {

       return file1;

    }

    public void setFile1(FormFile file1) {

       this.file1 = file1;

    }

在配置文件中配置上传文件的存储目录

首先,在WEB-INF目录下新建一个.properties文件里面存储想要存储的目录savedir=f/://strutsdemo//imgsv

创建一个单例类configManager

 

Public class configManager{

Priavete configManager(){}

Private static configManager instance = new configManager();

Public static configManager getInstance()

{

    Return instance;

}

Static String saveDir = null;

Public static String getSaveDir(String configPath)

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值