实现页面上传图片功能

页面代码:

   <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.   对于恶意图片的处理暂时没做处理 只能指望服务器的杀毒软件··有心情再研究把

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