美文网首页
二、commons-fileupload实现文件上传

二、commons-fileupload实现文件上传

作者: lifeline张 | 来源:发表于2018-07-15 11:22 被阅读0次

一、图片上传功能

image.png

二、具体步骤

如下:

第一步下载,commons-fileupload-1.2.2.jar和commons-io-2.4.jar

建议在API中参考使用到的类和接口

将jar导入项目中(WEB-INF/lib)

修改添加新闻的页面newsDetailCreateSimple.jsp,把表单提交到doAdd.jsp

注意:

1. 表单form标签中,method="post" enctype="multipart/form-data"

2. 上传图片的标签为:<input type="file" name="picPath" value=""/>

在doAdd.jsp中提取表单提交的新闻相关字段,并保存上传的文件,实现新闻的保存功能

注意:

1.需要在doAdd.jsp中导入需要的包

<%@page import="java.io.*,java.util.*,org.apache.commons.fileupload.*"%>

<%@page import="org.apache.commons.fileupload.disk.DiskFileItemFactory"%>

<%@page import="org.apache.commons.fileupload.servlet.ServletFileUpload"%>

请复制素材中的doAdd.jsp

2.在newsDetailList.jsp中点击“增加”打开newsDetailCreateSimple.jsp页面;“新闻标题”链接到newsDetailView.jsp并传递新闻Id参数,用以查看指定Id的新闻详情。

3.修改Dao和Service相关的类,完善“增加新闻信息”方法public boolean add(News news),增加“picPath”字段。增加“通过新闻id获取新闻”的方法public News getNewsById(int id)

新的doAdd.jsp的页面代码如下:

<%@page import="java.util.Date"%>
<%@page import="cn.kgc.pojo.News"%>
<%@page import="java.io.*,java.util.*,org.apache.commons.fileupload.*"%>
<%@page import="org.apache.commons.fileupload.disk.DiskFileItemFactory"%>
<%@page import="org.apache.commons.fileupload.servlet.ServletFileUpload"%>

<%@ 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>
<%@include file="../common/common.jsp" %>
<body>
<%
    //接收增加的新闻信息,并调用后台方法,将新闻信息插入数据库
    request.setCharacterEncoding("utf-8");
    boolean bRet = false;
    boolean bUpload = false;
    String uploadFileName = "";
    String fieldName = "";
    News news = new News();
    news.setCreateDate(new Date());
    //解析请求之前先判断请求类型是否为文件上传类型
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    //指定上传位置
    String uploadFilePath = request.getSession().getServletContext().getRealPath("upload/");
    System.out.println("uploadFilePath");
    File saveDir = new File(uploadFilePath);  
    //如果目录不存在,就创建目录  
    if(!saveDir.exists()){  
        saveDir.mkdir();  
    }  
    
    if(isMultipart){
        //创建文件上传核心类 
        FileItemFactory factory = new DiskFileItemFactory(); // 实例化一个硬盘文件工厂,用来配置上传组件ServletFileUpload
        ServletFileUpload upload = new ServletFileUpload(factory); // 用以上工厂实例化上传组件
        try{
            //处理表单请求
            List<FileItem> items = upload.parseRequest(request);
            Iterator<FileItem> iter = items.iterator();
            while(iter.hasNext()){
                FileItem item = (FileItem)iter.next();
                if(item.isFormField()){// 如果是普通表单控件 
                    fieldName = item.getFieldName();// 获得该字段名称
                    if(fieldName.equals("title")){
                        news.setTitle(item.getString("UTF-8"));//获得该字段值 
                    }else if(fieldName.equals("categoryId")){
                        news.setCategoryId(Integer.parseInt(item.getString()));
                    }else if(fieldName.equals("summary")){
                        news.setSummary(item.getString("UTF-8"));
                    }else if(fieldName.equals("newscontent")){
                        news.setContent(item.getString("UTF-8"));
                    }else if(fieldName.equals("author")){
                        news.setAuthor(item.getString("UTF-8"));
                    }
                }else{// 如果为文件域
                    String fileName = item.getName();// 获得文件名(全路径)
                    if(fileName != null && !fileName.equals("")){
                        File fullFile = new File(fileName);
                        File saveFile = new File(uploadFilePath,fullFile.getName());//将文件保存到指定的路径
                        item.write(saveFile);
                        uploadFileName = fullFile.getName();
                        news.setPicPath(uploadFileName);
                        bUpload = true;
                    
                    }
                
                }
            }
        }catch(Exception e){
            e.printStackTrace();
        }
        
    }   
    System.out.println("上传成功之后的文件名:" + news.getPicPath());
    //调用后台的方法,将新闻信息插入数据库中
    bRet = newsService.addNews(news);
    if(bRet)
        response.sendRedirect("newsDetailList.jsp");
    else
        response.sendRedirect("newsDetailCreateSimple.jsp");
    
%>

</body>
</html>

上面这段代码的逻辑是,先判断是否是上传文件的请求,如果是,则解析请求为一个集合,然后把集合里面的数据都拿出来,放到各自该放的地方去。

运行结果:


image.png

MyEclipse:


image.png
数据库中:

文件保存在Tomcat安装的地方中,这个项目部署的地方的新创建的upload文件夹中,在数据库中值保存了这个图片的地址信息。

三、Bug

image.png

原因:这个bug出现在我导入了common-upload的jar包,但是还没有改写程序中的增加新闻的方法的时候,之前的增加新闻的方法中没有路径,这就是bug的原因。这个bug应该是jsp页面找不要要调用的方法。
解决方法:改写新闻方法。

相关文章

网友评论

      本文标题:二、commons-fileupload实现文件上传

      本文链接:https://www.haomeiwen.com/subject/kfcppftx.html