java web開發 圖片上傳功能


基本思路在於,配置路徑,然后用java I/O的api將圖片上傳到該目錄下。

String photoPath =
   ServletActionContext.getServletContext().getRealPath("/user/photo/" + username);

這句是獲取服務器下的目錄+username

而username通過session獲取。

這是一個圖片上傳action的方法:

    public String execute() throws Exception {
        //獲得username
        Map session = ServletActionContext.getContext().getSession();
        String username = (String) session.get("username");
        
        //創建一個輸入流
        InputStream is = new FileInputStream(myFile);
        //設置文件保存目錄
        String photoPath = 
            ServletActionContext.getServletContext().getRealPath("/user/photo/" + username);
        File filePhotoPath = new File(photoPath);
        if(!filePhotoPath.isDirectory()) {
            filePhotoPath.mkdir();
        }
        
        //解決中文文件名問題
        String extension = FilenameUtils.getExtension(this.getMyFileFileName());
        String filename = UUID.randomUUID().toString() + "."+ extension;
        
        //設置目標文件
        File tofile = new File(photoPath,filename);
        //使用輸出流來包裝目標文件
        OutputStream os = new FileOutputStream(tofile);
        byte[] buffer = new byte[1024];
        int length = 0;
        while((length = is.read(buffer)) > 0) {
            os.write(buffer, 0, length);
        }
        //關閉輸入流
        is.close();
        //關閉輸出流
        os.close();
        
        return this.SUCCESS;
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM