JavaWeb作业--Jsp文件上传(限制文件后缀名)

upload.jsp

<%@ page contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<!DOCTYPE html>
<html>
<head>
<meta  charset="utf-8">
<title>文件上传</title>
<script src="C:\Users\AKSJ\Desktop\JaveEEDay2\js\bootstrap-3.3.7-dist\js\jquery.min.js"></script>
</head>
<body>
  <form action="${pageContext.servletContext.contextPath}/uploadServlet" name="one" enctype="multipart/form-data" method="post">
    选择一个文件:
    <input type="file" name="fileupload" value="upload" /> 
    <input type="submit" value="上传">
  </form>
 </body>
</html>

upload.java

package abc;

import java.io.*;
import java.util.*;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.filefilter.SuffixFileFilter;

@WebServlet(name="CheckNameServlet",urlPatterns={"/uploadServlet"})

public class Upload 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");
    	    response.setCharacterEncoding("utf-8");
    	    response.setContentType("text/html");
    	    PrintWriter out = response.getWriter();
    	    String uploadpath = "";
    	    DiskFileItemFactory factory = new DiskFileItemFactory();
    	    factory.setSizeThreshold(30 * 1024);
    	    factory.setRepository(factory.getRepository());
    	    ServletFileUpload upload = new ServletFileUpload(factory);
    	    List list = null;
    	    try{
    	      list = upload.parseRequest(request);
    	      String[] limit = new String[]{".html", ".exe", ".jsp"};
    	      SuffixFileFilter filter = new SuffixFileFilter(limit);
    	      Iterator iterator = list.iterator();
    	      while(iterator.hasNext()){
    	        FileItem item =(FileItem)iterator.next();
    	        if(!item.isFormField()){
    	          String filePath = item.getName();
    	          if(filePath != null){
    	            File filename= new File(filePath);
    	            File uploadFile = new File(request.getSession().getServletContext().getRealPath("/") + "upload");
    	            uploadpath = uploadFile.getAbsolutePath()+File.pathSeparator + uploadpath;
    	            uploadpath = uploadpath.substring(0, uploadpath.length()-1);
    	            File saveFile = new File(uploadpath,filename.getName());
    	            boolean flag = filter.accept(saveFile);
    	            if(flag){
    	              out.print("禁止上传此类型的文件");
    	              break;
    	            }else{
    	              try {
    	                item.write(saveFile);
    	                out.print("文件上传成功");
    	              } catch (Exception e) {
    	                out.print("文件上传失败了");
    	                e.printStackTrace();
    	              }
    	            }
    	          }
    	        }
    	      }
    	    }catch(Exception e){
    	      e.printStackTrace();
    	    }
    	  }  
}
运行结果:


  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值