文件上传功能

4.2 文件上传

文件上传功能需要前台功能和后台功能共同配合完成

前台:文件上传的三要素

  • 页面提供文件上传的表单元素type=file
    在这里插入图片描述

  • form表单enctype属性的值为multipart/form-data
    在这里插入图片描述

  • 表单的提交方式必须是POST,get方式无法提交大量的数据

后台:可以使用的技术有很多,在此处我们使用apache提供的commons-fileupload组件完成文件上次操作,后台的操作步骤如下

  • 确认请求操作是否支持文件上传
  • 创建磁盘工厂对象,用于将页面上传的文件保存到磁盘中
  • 获取servet文件上传核心对象
  • 读取数据
  • 对读取到数据中的文件表单进行操作,并将内容写到指定位置

完成文件上传的代码

private void testUpload(HttpServletRequest request,HttpServletResponse response) throws Exception {
    //1.确认该操作是否支持文件上传操作,enctype="multipart/form-data"
    if(ServletFileUpload.isMultipartContent(request)){
        //2.创建磁盘工厂对象
        DiskFileItemFactory factory = new DiskFileItemFactory();
        //3.Servlet文件上传核心对象
        ServletFileUpload fileUpload = new ServletFileUpload(factory);
        //4.从request中读取数据
        List<FileItem> fileItems = fileUpload.parseRequest(request);

        for(FileItem item : fileItems){
            //5.当前表单是否是文件表单
            if(!item.isFormField()){
                //6.从临时存储文件的地方将内容写入到指定位置
                item.write(new File(this.getServletContext().getRealPath("upload"),item.getName()));
            }
        }
    }
}

文件上传重名问题的解决

(1)修改业务层接口QuestionService的保存方法,添加返回值,将图片的名称返回

/**
     * 添加
     * @param question
     * @return 保存的图片名称
     */
String save(Question question);

(2)修改实现类,添加对图片名称的存储及返回图片的名称,图片名称使用该条数据的id

@Override
public String save(Question question) {
    SqlSession sqlSession = null;
    try{
        //1.获取SqlSession
        sqlSession = MapperFactory.getSqlSession();
        //2.获取Dao
        QuestionDao questionDao = MapperFactory.getMapper(sqlSession,QuestionDao.class);
        //id使用UUID的生成策略来获取
        String id = UUID.randomUUID().toString();
        question.setId(id);

        //设置新创建的题目默认的审核状态为未审核(0)
        question.setReviewStatus("0");
        question.setCreateTime(new Date());
        //设置当前存储的图片名称为id值
        question.setPicture(id);

        //3.调用Dao层操作
        questionDao.save(question);
        //4.提交事务
        TransactionUtil.commit(sqlSession);
        return id;
    }catch (Exception e){
        TransactionUtil.rollback(sqlSession);
        throw new RuntimeException(e);
        //记录日志
    }finally {
        try {
            TransactionUtil.close(sqlSession);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}

(3)在servlet中的save方法中接收图片名称

private void save(HttpServletRequest request,HttpServletResponse response) throws Exception {
    //1.确认该操作是否支持文件上传操作,enctype="multipart/form-data"
    if(ServletFileUpload.isMultipartContent(request)){
        //2.创建磁盘工厂对象
        DiskFileItemFactory factory = new DiskFileItemFactory();
        //3.Servlet文件上传核心对象
        ServletFileUpload fileUpload = new ServletFileUpload(factory);
        //4.从request中读取数据
        List<FileItem> fileItems = fileUpload.parseRequest(request);
        // --处理form表单提交过来的普通数据
        //将数据获取到,封装成一个对象
        Question question = BeanUtil.fillBean(fileItems,Question.class);
        //调用业务层接口save
        String picture = questionService.save(question);

        // --处理form表单提交过来的文件数据
        for(FileItem item : fileItems){
            //5.当前表单是否是文件表单
            if(!item.isFormField()){
                //6.从临时存储文件的地方将内容写入到指定位置
                item.write(new File(this.getServletContext().getRealPath("upload"),picture));
            }
        }
    }
    //跳转回到页面list
    response.sendRedirect(request.getContextPath()+"/store/question?operation=list");
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值