Struts1框架四之文件上传

整理笔记四,利用struts1实现文件上传,我在这里做一个简短的讲解
首先,我们需要配置一个jsp页面,让用户可以选择上传的文件

这里写图片描述
这里需要注意几点
1、请求为post请求,否则会报Element tyep unmatch异常。个人觉得原因可能为get请求时将请求信息封装在http请求头,但是请求头是有长度限制的,所以你需要将文件放在请求体里面。当然如果你上传的文件小于2K,也可以用get请求(struts1不在这个如果内)
2、需要一个type=”file”类型的from表单
3、注意需要在form表单后面填写enctype=”multipart/form-data”
配置struts-config.xml的form-bean和配置平常的form-bean是一样的

但是注意这个Student-Bean对象里面的属性

这样就完成了接受上传文件的收集,我们来看看怎么使用这个接口
package com.xingyao.action;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;

import com.xingyao.model.UserFile;

/**
* 登入功能的action
* @author xingyao
* @since 2016-8-24
*/
@SuppressWarnings(“all”)
public class LoginAction extends Action{

/**
 * 接受到请求信息,执行下面的代码,完成用户功能
 */
public ActionForward execute(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {

    //这个from就是接受到的表单信息,你可以直接进行强制转换
    UserFile student_Bean =  (UserFile) form;
    FormFile formFile = student_Bean.getMyFile();

    //得到项目路径
    String projectPath = LoginAction.class.getClassLoader().getResource("").toString();
    projectPath = projectPath.replace("file:/", "");

    //判断文件是否存在,如果不存在,则创建
    File file = new File(projectPath+"file/");
    if(!file.exists()){
        file.mkdirs();
    }else{
        //设置得到文件的名称的编码格式为UTF-8
        String s = new String(formFile.getFileName().getBytes(),"utf-8");
        OutputStream os = new FileOutputStream(file+"/"+s);
        os.write(formFile.getFileData());
        os.flush();
    }
    //返回结果,拥有返回页面的判断,参照配置文件(struts-config.xml)里面的<forward name="success" path="/WEB-INF/JSP/success.jsp"></forward>
    return mapping.findForward("success");
}

}
转载请标明出处
感谢苏波老师的指导
个人见解、错误请指出!请莫怪

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值