文件上传

1文件上传

实现图片上传(要求限制后缀以及图片的大小,将图片存储到指定的服务器中,地址存储到数据库中,最后在页面中显示出来)

文件上传需要满足以下条件

1.表单的提交属性中要有enctype=“multipart/form-data”(用于标注这是一个文件上传的表单)

2.表单的提交方式必须为POST

实现步骤:

1.关联图片上传的jar包(commons-io.jar、commons-fileupload.jar),数据库驱动包以及jstl相关的jar包(是否需要使用jstl)

2.定义表单,指定enctype属性以及提交方式为post,同时给定input类型为file的表单

3.解析提交的表单数据(request)

​ a.创建一个DiskFileItemFactory对象,作为ServletFileupload对象的工厂

​ b.创建ServletFileupload对象,通过该对象去解析request对象,返回一个FileItem集合对象

​ c.每个FileItem中包含的就是表单中对应的键值对

​ d.判断是否是文件对象

4.截取上传的文件的后缀与指定的后缀名进行匹配

5.给上传的文件起个新名字以保证名字不冲突(UUID、时间戳等等)

6.将该过名字的文件写入到指定的服务器的地址中

7.将文件的地址写入到数据库中进行存储

8.在前端的页面中显示上传的图片

前端添加页面

<c:if test="${not empty picSuffix}">
  <p>只能上传:${picSuffix}</p>
</c:if>
<c:if test="${not empty sizeMsg}">
  <p>${sizeMsg}</p>
</c:if>
<c:remove var="sizeMsg"/>
<c:remove var="picSuffix"/>
<form action="fileUploadServlet" enctype="multipart/form-data" method="post">
  <input type="text" name="uname">
  <input type="file" name="file">
  <input type="submit" value="提交">
</form>

后台上传代码

request.setCharacterEncoding("utf-8");
HttpSession session = request.getSession();
//需要一个读取磁盘的工厂对象
FileItemFactory factory = new DiskFileItemFactory();
//通过工厂生产ServletFileUpload
ServletFileUpload fileUpload = new ServletFileUpload(factory);
try {
  //设置可上传的文件大小
  fileUpload.setSizeMax(1024*10);
  //定义可以上传的文件后缀格式
  String[] suffixArr = {".png",".jpg",".gif",".jpeg"};
  //解析request对象
  List<FileItem> fileItemList = fileUpload.parseRequest(request);
  //遍历表单中的key val集合,拿到每一个具体的fileItem对象(包含了key和val值)
  for(FileItem fileItem : fileItemList){
    //判断当前的fileItem是普通的表单数据还是一个文件上传对象
    if(fileItem.isFormField()){//true代表是普通的表单字段
      String fieldName = fileItem.getFieldName();
      String fieldVal = fileItem.getString();
    } else{//false代表是文件上传字段
      String fieldName = fileItem.getFieldName();
      //getName()获取上传的文件的名字
      String fieldVal = fileItem.getName();
      //获取上传的文件的后缀
      int lastIndex = fieldVal.lastIndexOf(".");
      String suffix = fieldVal.substring(lastIndex);
      //判断上传的文件后缀是否存在于指定的格式中
      List<String> suffixList = Arrays.asList(suffixArr);
      if(!suffixList.contains(suffix)){
        session.setAttribute("picSuffix",suffixList);
        resp.sendRedirect("index.jsp");
        return;
      } else{
        /*
        * 开发中存储图片的方式
        * 1.转为base64存储到数据库(不推荐)
        * 2.图片存储到服务器上,图片所在的地址存储到数据库中
        * */
        //获取服务器中存储图片的文件夹地址
        String realPath = request.getRealPath("/upload");
        //将图片写入到指定的服务器地址中
        File file = new File(realPath);
        if(!file.exists()){
          //如果文件不存在就创建下
          file.mkdir();
        }
        //为文件生成一个随机的名字,以保证名字不冲突(此处使用UUID生成)
        //59685860-8d89-4b73-ba56-3fe9a27f11fd
        String uuid = UUID.randomUUID().toString();
        String fileName = uuid.replace("-","")+suffix;
        File writeFile = new File(realPath,fileName);
        fileItem.write(writeFile);
        //将图片的路径存储到数据库中
        String sql = "insert into t_item(pic) values(?)";
        DBUtil.curd(sql,fileName);
        //跳转到显示页面
        resp.sendRedirect("show_pic.jsp");
        return;
      }
    }
  }
} catch (SizeLimitExceededException e){
  session.setAttribute("sizeMsg","可上传的文件大小为:"+fileUpload.getSizeMax()/1024+"KB");
  resp.sendRedirect("index.jsp");
} catch (FileUploadException e) {
  e.printStackTrace();
} catch (Exception e) {
  e.printStackTrace();
}

前端展示代码

<%--此处应该通过三层架构获取数据库中的数据进行使用--%>
<%
//getContextPath()获取服务器的根目录地址
//request.getServletPath() 获取servlet地址
//request.getServletContext().getRealPath()获取上下文对象的绝对地址(对应磁盘地址)
String serverPath = request.getContextPath();
//图片存储路径
String picPath = serverPath + +"/upload/";
//获取到数据库中的图片路径集合
List<Picture> pictureList = new ArrayList<>();
Connection connection = DBUtil.newInstance();
String sql = "select * from t_item";
PreparedStatement preparedStatement = connection.prepareStatement(sql);
ResultSet resultSet = preparedStatement.executeQuery();
while(resultSet.next()){
  Picture picture = new Picture();
  picture.setId(resultSet.getInt(1));
  picture.setPic(resultSet.getString(2));
  pictureList.add(picture);
}
//存到域中
session.setAttribute("pictureList",pictureList);
%>
<c:forEach items="${pictureList}" var="picture">
  <img src="<%=picPath%>${picture.pic}" alt="" width="300px" height="300px" border="1px">
</c:forEach>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值