struts2文件上传

    xiaoxiao2023-10-29  137

    一、文件上传页面四个要求:

    (1)变短必须是post提交

    (2)提交类型必须是enctype="multipart/form-data",必须多段式

    (3)文件使用文件上传控件<input type="file“ name="f"/>

    (4)name必填,不然不会上传

    二、使用struts2接受文件

    1、后台接受文件:

    在action中写一个File对象的属性,属性名和前台的name相同,struts2就回把文件自动封装到该对象

    然后img.renameTo(new File("E:/upload/my.jpg"));就可以保存到本地

    2、后台接受文件名:

    在action中写一个属性,属性名为提交name+固定后缀FileName,文件名称就回自动封装到属性中

    3、接受文件MIME类型:

     在action中写一个属性,属性名为提交name+固定后缀名ContentType,文件MIME类型会自动封装到属性中text/html

    4、struts2文件上传原理:

    fileUpload拦截器中提取信息,然后在params拦截器中放入

    5、其他表单属性不用经过处理,照之前的一样获得

    三、例子:

    前台:

    <form action="${pageContext.request.contextPath }/customerAction_saveOrUpdate" method="post" enctype="multipart/form-data"> <div class="inputItem"> <label>图片上传 :</label> <input type="file" name="customerImage" /> </div> <div class="inputItem"> <input type="submit" value="添加" class="submitButton"/> </div> </form>

    后台:(为了方便看获得的文件名和文件MIME类型,在控制台输出了一下)

    public class CustomerAction extends ActionSupport implements ModelDriven<Customer> { //文件属性 private File customerImage; private String customerImageFileName; private String customerImageContentType; public String saveOrUpdate() { //获得图片保存的路径 String realPath = ServletActionContext.getServletContext().getRealPath("/uploadImage"); //保存图片 customerImage.renameTo(new File(realPath+"\\"+customerImageFileName)); //输出真实路径 System.out.println(realPath); //输出文件名 System.out.println(customerImageFileName); //输出文件MIME类型 System.out.println(customerImageContentType); return "toList"; } }

    控制台输出:

    最新回复(0)