實現頁面上傳圖片功能

頁面代碼:

   <input type="file" name="picture"/>上傳圖片<br/>

重點在表單提交的時候要加上一個屬性

<formmethod="post" id="form" action="register!inland_p.action"enctype="multipart/form-data">

在antion獲取的時候:

定義3個變量

    private File picture;

    private String pictureContentType;

    private String pictureFileName;

分別加上set方法

Struts2會自動把圖片文件傳到action

保存到指定路徑:

// 保存圖片

    privatevoid savaImage(File picture, String path, StringpictureFileName) {

 

       FileInputStream in = null;

       FileOutputStream out = null;

       BufferedInputStream bufferedIn = null;

       BufferedOutputStream bufferedOut = null;

       try {

           // 保存圖片到本地

           in = new FileInputStream(picture);

           out = new FileOutputStream(path + pictureFileName);

           bufferedIn = new BufferedInputStream(in);

           bufferedOut = new BufferedOutputStream(out);

           byte[] data = newbyte[1];

           while (bufferedIn.read(data) != -1) {

              bufferedOut.write(data);

           }

           // 將緩衝區中的數據全部寫出

           bufferedOut.flush();

           // 關閉流

           in.close();

           out.close();

           bufferedIn.close();

           bufferedOut.close();

       } catch (Exception e) {

           e.printStackTrace();

       } finally {

           try {

              // 關閉流

              if (in != null) {

                  in.close();

              }

              if (out != null) {

                  out.close();

              }

              if (bufferedIn != null) {

                  bufferedIn.close();

              }

              if (bufferedOut != null) {

                  bufferedOut.close();

              }

           } catch (IOException e) {

              e.printStackTrace();

           }

       }

    }

 

校驗圖片的幾種方法:(具體網上可查代碼)

1.   判斷文件類型

2.   判斷文件前幾個字符

3.   判斷文件的長和寬確定是不是圖片(推薦)

4.   對於惡意圖片的處理暫時沒做處理 只能指望服務器的殺毒軟件··有心情再研究把

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章