图片的上传

1:使用apache的插件:commons-fileupload.jar实现附件的上传
2:编写页面:upload.jsp
3:编写上传附件servlet:PicUploadServlet.java
4:配置web.xml

upload.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<!-- 二进制表单 1:post请求 2:enctype="multipart/form-data" -->
<form action="${pageContext.request.contextPath}/picUpload"
 enctype="multipart/form-data" method="post">
 username:<input type="text" name="username"><br/>
 <input type="file" name="file"><br/>
 <input type="submit" value="上传">
</form>

</body>
</html>

PicUploadServlet.java

package com.itany.servlet;

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Calendar;
import java.util.Iterator;
import java.util.List;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

public class PicUploadServlet extends HttpServlet
{
   //定义一个在硬盘中存放的一个临时目录
    private File  tempPath=null;
    //定义保存上传文件的目录
    private File uploadPath=null;
    /**
     * 初始化上传目录
     */
    @Override
    public void init()
        throws ServletException
    {
       //取得临时目录
       tempPath=new File( this.getServletContext().getRealPath("temp"));
       //如果目录不存在,创建一个目录
      if(!tempPath.exists())
      {
          tempPath.mkdir();
      }
      //获取上传的路径
      uploadPath=new File( this.getServletContext().getRealPath("upload/images"));
      //如果该目录不存在,创建一个
      if(!uploadPath.exists())
      {
          //创建多级目录
          uploadPath.mkdirs();
      }
    }
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException
    {
      
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException
    {
        //创建工厂类
        DiskFileItemFactory factory =new DiskFileItemFactory();
        //设置文件块的大小 4k
        factory.setSizeThreshold(4096);
        //设置临时目录
        factory.setRepository(tempPath);
        //创建上传组件对象
       ServletFileUpload upload =new ServletFileUpload(factory);
       //设置上传文件的大小4M
       upload.setSizeMax(4096000);
       
           try
        {
             //得到元素列表
           List fileItems= upload.parseRequest(req);
           //遍历该元素列表
           Iterator iter =fileItems.iterator();
           String username;
           while(iter.hasNext())
           {
             FileItem item=(FileItem)iter.next();
             //普通表单元素
             if(item.isFormField())
             {
                 if("username".equals(item.getFieldName()))
                 {
                     username=item.getString("utf-8");
                     System.out.println(username);
                 } 
             }
              //如果是上传表单域
            else    
            {
               //获取文件名
              String fileName = item.getName();
              //获取文件后缀名
            String ext=fileName.substring(fileName.lastIndexOf(".")+1,fileName.length());
             //获取新的随机的文件名(不会重复)
             Calendar calendar  =Calendar.getInstance();
             //以当前的毫秒值作为文件名
            fileName= String.valueOf(calendar.getTimeInMillis());
            //文件的全路径
            String fullFilepPath=uploadPath+File.separator+fileName+"."+ext;
            //将临时文件写到磁盘上
            File f =new File (fullFilepPath);
             item.write(f);
             //以上代码完成了原图的上传
             //以下代码完成将原图生成一张缩略图
             String newurl =uploadPath+File.separator+fileName+"_min."+ext;
             //构造image对象
             Image src=ImageIO.read(f);
             //目标大小(一边为200px,另一边自适应)
             float tagSize =200;
             //得到原图的高和宽
            int old_w =src.getWidth(null);
            int old_h=src.getHeight(null);
            //定义新图的宽和高
            int new_w=0;
            int new_h=0;
            //申明中间值
            float tempDouble;
            //根据宽和高得到临时的比例
            if(old_w>old_h)
            {
                tempDouble =old_w/tagSize; 
            }
            else 
            {
                tempDouble =old_h/tagSize; 
            }
            //得到新的宽度和高度
            new_w=Math.round(old_w/tempDouble);
            new_h=Math.round(old_h/tempDouble);
            //创建新图像
           BufferedImage tag =new BufferedImage(new_w,new_h,BufferedImage.TYPE_INT_RGB);
           //绘制缩小后的图片
           tag.getGraphics().drawImage(src,0,0,new_w,new_h,null);
           //创建新的文件路径
           FileOutputStream newImg =new FileOutputStream(newurl);
           //创建编码对象
           JPEGImageEncoder encoder =JPEGCodec.createJPEGEncoder(newImg);
           //JPEG编码
           encoder.encode(tag);
           newImg.close();
           //转发到上传成功页面
           req.getRequestDispatcher("success.jsp").forward(req, resp);
            }
          }
        }
        catch (FileUploadException e)
        {
            
            e.printStackTrace();
        }
        catch (Exception e)
        {
           
            e.printStackTrace();
        }
    }
    
}


web.xml

   <servlet>
    <servlet-name>picUploadServlet</servlet-name>
    <servlet-class>com.itany.servlet.PicUploadServlet</servlet-class>
  </servlet>
  
  <servlet-mapping>
     <servlet-name>picUploadServlet</servlet-name>
     <url-pattern>/picUpload</url-pattern>
   </servlet-mapping>




 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值