欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

判断上传文件是否为图片

程序员文章站 2024-02-19 19:28:34
...

1.创建前端页面,设置表单

<html>
  <head>
    <title>$Title$</title>
  </head>
  <body>
  <%=session.getAttribute("picSuffix")%>


 <form action="fileselevet" enctype="multipart/form-data"  method="post">
<input  type="text" name="uname">
   <input type="file" name="file">
   <input type="submit" value="提交">
 </form>
  </body>
</html>

2.用servlet实现

@WebServlet("/fileselevet")
public class fileselevet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
       //设置编码格式
         request.setCharacterEncoding("utf-8");
         HttpSession session =request.getSession();
         //读取磁盘工厂对象
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload fileUpload = new ServletFileUpload(factory);
        String[] suffixArr = {".jpg",".png",".gif"};
        try {
            List<FileItem> fileItemList = fileUpload.parseRequest(request);
            for(FileItem fileItem :fileItemList){
                if(fileItem.isFormField()){//是普通字段
                    String fieldNmae = fileItem.getFieldName();
                    String fieldVal = fileItem.getString();

                }else {
                    String fieldNmae = fileItem.getFieldName();
                    String fieldVal = fileItem.getName();
                    //获取上传文件的后缀
                    int lastIndex = fieldVal.lastIndexOf(".");
                    String suffix = fieldVal.substring(lastIndex);
                    //判断上传文字后缀是否存在于
                    //数组转换为集合 这个list集合是list集合封装后的list
                    List<String> suffixList = Arrays.asList(suffixArr);
                    if(!suffixList.contains(suffix)){
                        session.setAttribute("picSuffix",suffixList);
                        response.sendRedirect("index.jsp");
                        return;
                    }
                }
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
        }

    }
}
相关标签: java js web