使用Struts2上傳圖片

在Struts2中爲咱們提供了比較簡單的文件上傳方式.html

首先引入commons-fileupload-x.jar、commons-io-x.jar 這兩個jar包,而後引入Struts2相關jar包java

 

接下來新建一個jsp文件:寫一個文件上傳表單,這裏須要特別注意要在form加上enctype="multipart/form-data"  method="post" .session

<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類:dom

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的規則.jsp

 

Struts2默認文件的上傳大小是2M,當大於2M時會拋出異常,這裏咱們能夠在struts.xml文件裏作以下配置,控制上傳文件的大小:ide

<struts>    
<constant name="struts.multipart.maxSize" value="10485761"/>     
</struts>
相關文章
相關標籤/搜索