上传图片到服务器并将图片路径保存到数据库

首先需要准备两个包:commons-io-2.2.jar和commons-fileupload-1.3.3.jar

doPost:

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

            //判断上传的表单是否为multipart/form-data类型

            HttpSession session = request.getSession();

            User user = (User)session.getAttribute("user"); //在登录时将User对象放入会话。

            if(ServletFileUpload.isMultipartContent(request)) {

                    try{

                        //1.创建DiskFileItemFactory对象,设置缓冲区大小和临时文件

                        DiskFileItemFactory factory = new DiskFileItemFactory();

                        //2.创建ServletFileUpload对象,并设置上传文件大小限制

                        ServletFileUpload sfu = new ServletFileUpload(factory);

                        sfu.setFileSizeMax(10*1024*1024); //以byte为单位,不能超过10M

                         sfu.setHeaderEncoding("utf-8");

                            //3.调用ServletFileUpload.parseRequest方法解析request对象,得到一个保存了所有上传内容的List对象

                            @SuppressWarnings("unchecked")

                            List fileItemList = sfu.parseRequest(request);

                                Iterator fileItems = fileItemList.iterator();

                            //遍历list,没迭代一个FileItem对象,调用其isFormField方法判断是否上传文件

                            while(fileItems.hasNext()) {

                                    FileItem fileItem = fileItems.next();

                            //普通表单元素

                            if(fileItem.isFormField()){

                                    String name = fileItem.getFieldName();//name属性值

                                    String value = fileItem.getString("utf-8");

                                    System.out.println(name + "=" + value);

                        }else {

                                    String fileName = fileItem.getName();//文件名称

                                    System.out.println("原文件名:" +fileName);//.jpg

                                    String suffix = fileName.substring(fileName.lastIndexOf('.'));

                                    System.out.println("扩展名:" +suffix);

                                    //新文件名(唯一)

                                    String newFileName = new Date().getTime() +suffix;

                                    System.out.println("新文件名:" + newFileName);

                                    //5.调用FileItem的write()方法写入文件

                                    File file = new File("E:/workspae1/pets/WebContent/images/" + newFileName);

                                    System.out.println(file.getAbsolutePath());

                                    try {

                                        fileItem.write(file);

                                        //6.调用FileItem的delete()方法,删除临时文件

                                        fileItem.delete();

                                        /*

                                        * 存储数据库

                                          */

                                            UserImage userImage = new UserImage();

                                                if(user != null){

                                                String username = user.getUsername();

                                                userImage.updateimage("images/" + newFileName,username);

                                                session.setAttribute("image_name", fileName);

                                                session.setAttribute("image_path", newFileName);

}

                                                response.sendRedirect(request.getContextPath()+"/perinfo.jsp");

                                                } catch (Exception e) {

                                                // TODO Auto-generated catch block

                                            e.printStackTrace();

                                            }

                                        }

                                    }

                    }catch(FileUploadException e){

                e.printStackTrace();

                        }

}

 userImage.java中有个方法updateimage(String,String)。

我连接数据库的方式是用的mybatis,updateimage(String,String)方法实现了根据用户名更改图片路径。

html:

注意表单中必须加enctype="multipart/form-data"。


以上的方式可以实现图片上传到服务器,路径到数据库。每次上传需手动刷新数据库和webContent文件才能够显示出来。所以也就成了一个弊端,目前还在找解决办法。


        

你可能感兴趣的:(上传图片到服务器并将图片路径保存到数据库)