码迷,mamicode.com
首页 > 编程语言 > 详细

Java Web——图像上传

时间:2016-11-08 00:49:43      阅读:176      评论:0      收藏:0      [点我收藏+]

标签:extend   file   ted   ring   att   大小限制   创建   dir   存储   

一、jsp中:

 1 <body>
 2     <!-- 注意: 1. type="file"; 2.method="post" ; 3.enctype="multipart/form-data" -->
 3     <form action="UploadServlet" method="post" enctype="multipart/form-data">
 4         雇员编号:<input type="text" name="empno"/><br/><br/>
 5         雇员姓名:<input type="text" name="ename"/><br/><br/>
 6         所在部门:
 7                 <select name="deptno">
 8                     <option value="10">销售部</option>
 9                     <option value="20">IT部</option>
10                     <option value="30">人力部</option>
11                 </select><br/><br/>
12         验证码:<input type="text" name="code"><img id="code" alt="请刷新" src="validateCodeServlet" onclick="changeCode()" style="cursor:hand;"><a href="javascript:changeCode()">换一张</a><br/><br/>
13         
14             
15         头像:<input type="file" name="uploadFile">
16             <img src="${image_path}" title="${image_name}" width="200" height="200">
17         <br/><br/>
18         
19         <input type="reset" value="重置"/> 
20         <input type="submit" value="注册"/> 
21     </form>
22 </body>
23 </html>

 

 

 

二、导入工具包

 技术分享

三、servlet中取得数据

 

package servlet;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
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;

/**
 * Servlet implementation class UploadServlet
 */
@WebServlet("/UploadServlet")
public class UploadServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //判断上传表单是否为multipart/form-data类型
        if(ServletFileUpload.isMultipartContent(request))
        {
            
            try {
                //1. 创建DiskFileItemFactory对象,设置缓冲区大小和临时文件目录
                DiskFileItemFactory factory = new DiskFileItemFactory();
                //System.out.println(System.getProperty("java.io.tmpdir"));//默认临时文件夹
                
                //2. 创建ServletFileUpload对象,并设置上传文件的大小限制。
                ServletFileUpload  sfu = new ServletFileUpload(factory);
                sfu.setSizeMax(10*1024*1024);//以byte为单位    不能超过10M  1024byte = 1kb  1024kb=1M 1024M = 1G
                sfu.setHeaderEncoding("utf-8");
                
                //3. 调用ServletFileUpload.parseRequest方法解析request对象,得到一个保存了所有上传内容的List对象。
                List<FileItem> fileItemList = sfu.parseRequest(request);
                Iterator<FileItem> fileItems = fileItemList.iterator();
                
                //4. 遍历list,每迭代一个FileItem对象,调用其isFormField方法判断是否是上传文件
                while(fileItems.hasNext())
                {
                    FileItem fileItem = fileItems.next();
                    //普通表单元素
                    if(fileItem.isFormField())
                    {
                        String name = fileItem.getFieldName();//name属性值
                        String value = fileItem.getString("utf-8");//name对应的value值
                        
                        System.out.println(name + " = "+value);
                    }
                    //<input type="file">的上传文件的元素
                    else
                    {
                        String fileName = fileItem.getName();//文件名称
                        System.out.println("原文件名:" + fileName);//Koala.jpg
                        
                        String suffix = fileName.substring(fileName.lastIndexOf(‘.‘));
                        System.out.println("扩展名:" + suffix);//.jpg
                        
                        //新文件名(唯一)
                        String newFileName = new Date().getTime() + suffix;
                        System.out.println("新文件名:" + newFileName);//image\1478509873038.jpg
                        
                        //5. 调用FileItem的write()方法,写入文件
                        File file = new File(request.getServletContext().getRealPath("image")+"\\"+newFileName);
                        System.out.println(file.getAbsolutePath());
                        fileItem.write(file);
                        
                        //6. 调用FileItem的delete()方法,删除临时文件
                        fileItem.delete();
                        
                        /*
                         * 存储到数据库时注意
                         *     1.保存源文件名称   Koala.jpg
                         *  2.保存相对路径      image/1478509873038.jpg
                         * 
                         */
                        request.setAttribute("image_name",fileName);
                        request.setAttribute("image_path","image/"+newFileName);
                        request.getRequestDispatcher("/upload.jsp").forward(request, response);
                    }
                }
                
            } catch (FileUploadException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
            
            
        }
    }

}

 

Java Web——图像上传

标签:extend   file   ted   ring   att   大小限制   创建   dir   存储   

原文地址:http://www.cnblogs.com/ccw95/p/6040256.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!