使用Struts2上传图片

*爱你&永不变心* 提交于 2019-12-07 20:55:29

在Struts2中为我们提供了比较简单的文件上传方式.

首先引入commons-fileupload-x.jar、commons-io-x.jar 这两个jar包,然后引入Struts2相关jar包

 

接下来新建一个jsp文件:写一个文件上传表单,这里需要特别注意要在form加上enctype="multipart/form-data"  method="post" .

<s:form id="upload-form-1" name="upload-form-1"
        action="/user/bookAction!uploadbook" method="post"
        enctype="multipart/form-data">
        书籍名称:<input type="text" name="uploadbookform.book_name"/><br>
                书籍封页图:<input type="file" name="uploadbookform.book_pic"/><br>
        作者:<input type="text" name="uploadbookform.book_author"/><br>
        译者:<input type="text" name="uploadbookform.book_translator"/><br>
        内容简介:<input type="text" name="uploadbookform.publish_info"/><br>
        书籍分类:<input type="text" name="uploadbookform.book_labels"/><br>
        <input type="submit" >
    </s:form>

然后是写Action类:

public class BookAction extends ActionSupport implements RequestAware {
    private Map<String, Object> request;
    private Map<String, Object> session = ActionContext.getContext()
            .getSession();
    
    @Override
    public void setRequest(Map<String, Object> request) {
        // TODO Auto-generated method stub
        this.request = request; // 将该方法中的request赋值给成员变量request
    }

    @Resource(name = "bookManage")
    private BookServiceImpl bookservice;

    private List<Book> booklist;
    private UploadBookForm uploadbookform;
    private static final long serialVersionUID = 1L;

    public UploadBookForm getUploadbookform() {
        return uploadbookform;
    }

    public void setUploadbookform(UploadBookForm uploadbookform) {
        this.uploadbookform = uploadbookform;
    }
/**
     * 上传书籍(同时书籍含有自定义标签)
     * 
     * @return
     */
    public String uploadbook() {
        String realPath = ServletActionContext.getServletContext().getRealPath("/BookImage");
        
         SimpleDateFormat date = new SimpleDateFormat("/yyyy/MM/dd");  
            String dateTime = date.format(new Date());  
            realPath += dateTime;  
              
            uploadbookform.setBook_picFileName(UUID.randomUUID().toString() + uploadbookform.getBook_picFileName().substring(uploadbookform.getBook_picFileName().lastIndexOf('.')));  
              
            System.out.println(uploadbookform.getBook_picContentType());   
            //控制图片类型  
            if(uploadbookform.getBook_picContentType().equals("image/gif") || uploadbookform.getBook_picContentType().equals("image/jpeg") ||   
                    uploadbookform.getBook_picContentType().equals("image/png") || uploadbookform.getBook_picContentType().equals("image/bmp") ||   
                    uploadbookform.getBook_picContentType().equals("image/x-icon") || uploadbookform.getBook_picContentType().equals("image/pjpeg"))  
            {  
                //判断文件是否为空,并且文件不能大于2M  
                if(uploadbookform.getBook_pic() != null && uploadbookform.getBook_pic().length() < 2097152)  
                {    
                    //根据 parent 抽象路径名和 child 路径名字符串创建一个新 File 实例。  
                    File filePath = new File(new File(realPath), uploadbookform.getBook_picFileName());    
                    //判断路径是否存在    
                    if(!filePath.getParentFile().exists())  
                    {  
                        //如果不存在,则递归创建此路径   
                        filePath.getParentFile().mkdirs();  
                    }  
                    System.out.println(uploadbookform.getBook_picFileName());   
                    System.out.println(filePath.getParentFile());   
                    //将文件保存到硬盘上,Struts2会帮我们自动删除临时文件  
                    try {  
                        FileUtils.copyFile(uploadbookform.getBook_pic(), filePath);  
                    } catch (IOException e) {  
                        System.out.println("图片上传失败");   
                        e.printStackTrace();  
                    }   
                }    
            } 
        
        bookservice.uploadBook(uploadbookform);
        addActionMessage("上传成功");
        return "uploadbooksuccess";
    }
    }

上面还是要遵守约定大于配置,注意名称的命名,uploadFileContentType和uploadFileFileName必须遵守Struts2的规则.

 

Struts2默认文件的上传大小是2M,当大于2M时会抛出异常,这里我们可以在struts.xml文件里做如下配置,控制上传文件的大小:

<struts>    
<constant name="struts.multipart.maxSize" value="10485761"/>     
</struts>


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!