common-fileupload上傳圖片並顯示圖片

效果圖以下:javascript

                                 

代碼:html

注意:須要jar包:commons-fileupload-1.2.1.jar  和 commons-io-1.4.jarjava

index.jsp緩存

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
    <head>
        <title>添加圖片</title>
        <script type="text/javascript">
            //打開上傳頁面
            function openUpload(){
                var win = window.showModalDialog("/upload.jsp","","dialogWidth:300px;dialogHeight:200px;scroll:no;status:no");
                if(win != null){
                    document.getElementById("photo_id").value = win;
                    document.getElementById("img_id").src = "/"+win;
                }
            }
        </script>
    </head>
    <body>
        <h5>添加圖片</h5><hr/>
            <p>
                上傳圖片:
                <label>
                    <input type="hidden" id="photo_id" name="photo" value="images/default.gif">
                    <input type="button" onclick="openUpload()" value="上傳圖片"/><br/>
                    <img id="img_id" alt="" src="/images/default.gif" width="200px" height="200px">
                </label>
            </p>
      </body>
</html>
upload.jsp
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=GBK">
        <meta http-equiv="pragma" content="no-cache" />
        <span style="color: #ff0000;"><base target="_self"></span>
        <title>圖片上傳</title>
    </head>
    <body>
        <h5>圖片上傳</h5><hr/>
        <p style="color: red">${requestScope.errorMsg}</p>
        <form id="form1" name="form1" action="/servlet/Upload" method="post" enctype="multipart/form-data">
            <div>注:圖片大小最大不能超過3M!</div>
            <div>
                <input type="file" name="file_upload"/>
                <input type="submit" value="上傳"/>
            </div>
        </form>
    </body>
</html>
Upload.java 中的主要代碼:
public class Upload extends HttpServlet {

    private String uploadPath = "aa/upload/"; // 上傳文件的目錄  
    private String tempPath = "aa/uploadtmp/"; // 臨時文件目錄  
    private String serverPath = null;
    
    private int sizeMax = 3;//圖片最大上限
    private String[] fileType = new String[]{".jpg",".gif",".bmp",".png",".jpeg",".ico"};
    
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html");
        response.setCharacterEncoding("utf-8"); //設置編碼,方式返回的中文亂碼
        
        serverPath = getServletContext().getRealPath("/").replace("\\", "/");
        //Servlet初始化時執行,若是上傳文件目錄不存在則自動建立
        if(!new File(serverPath+uploadPath).isDirectory()){
            new File(serverPath+uploadPath).mkdirs();
        }
        if(!new File(serverPath+tempPath).isDirectory()){
            new File(serverPath+tempPath).mkdirs();
        }

        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(5*1024); //最大緩存
        factory.setRepository(new File(serverPath+tempPath));//臨時文件目錄
        
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setSizeMax(sizeMax*1024*1024);//文件最大上限
        
        String filePath = null;
        try {
            List<FileItem> items = upload.parseRequest(request);//獲取全部文件列表
            for (FileItem item : items) {
                //得到文件名,這個文件名包括路徑
                if(!item.isFormField()){
                    //文件名
                    String fileName = item.getName().toLowerCase();
                    
                    if(fileName.endsWith(fileType[0])||fileName.endsWith(fileType[1])||fileName.endsWith(fileType[2])||fileName.endsWith(fileType[3])||fileName.endsWith(fileType[4])||fileName.endsWith(fileType[5])){
                        String uuid = UUID.randomUUID().toString();
                        filePath = serverPath+uploadPath+uuid+fileName.substring(fileName.lastIndexOf("."));
                        item.write(new File(filePath));
                        PrintWriter pw = response.getWriter();
                        pw.write("<script>alert('上傳成功');window.returnValue='"+uploadPath+uuid+fileName.substring(fileName.lastIndexOf("."))+"';window.close();</script>");
                        pw.flush();
                        pw.close();
                    }else{
                        request.setAttribute("errorMsg", "上傳失敗,請確認上傳的文件存在而且類型是圖片!");
                        request.getRequestDispatcher("/upload.jsp").forward(request,response);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("errorMsg", "上傳失敗,請確認上傳的文件大小不能超過"+sizeMax+"M");
            request.getRequestDispatcher("/upload.jsp").forward(request,response);
        }
    }

}

 

 <p style="color: red">${requestScope.errorMsg}</p>

表示變量的做用域,一共4種。session

pageScope: 表示變量只能在本頁面使用。app

requestScope:表示變量能在本次請求中使用。dom

sessionScope:表示變量能在本次會話中使用。jsp

applicationScope:表示變量能在整個應用程序中使用。post

 

源碼下載地址:http://download.csdn.net/detail/u011518709/7885625ui

相關文章
相關標籤/搜索