JSP+servlet上传文件

在网上找了好些,都不是很适合,从以前的工程里找了个,先收藏下,要不下次有的找好长时间!

------------------------upload.jsp-------------------------

<body>
<br>
<h1 align="center">上传文件</h1>
<hr>
<form action="FileUploadServlet" method="post" enctype="multipart/form-data" name="form1">
    <div align="center">
      <input type="file" name="file">
      <input type="submit" name="Submit" value="提交">
    </div>
</form>
  
</body>

---------------------------servlet------------------

public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {

   response.setContentType("text/html");
   PrintWriter out = response.getWriter();
  
   /* 初始化JSPSmart变量 */
   SmartUpload mySmartUpload = new SmartUpload();
   Date date = new Date();
   //String allowedFilesList = "doc,DOC,pdf,PDF,txt,TXT,html,HTML,htm,HTM";
   String allowedFilesList ="mdb";
    Files fils = null;
   int maxFileSize = 100 * 1024*1024;
   Request req = null;
   //站点根目录
   ServletConfig config = getServletConfig();// 得到servletConfig
   mySmartUpload.initialize(config, request, response);
   mySmartUpload.setMaxFileSize(maxFileSize); // 上传文件的大小
   mySmartUpload.setAllowedFilesList(allowedFilesList);// 允许上传的格式
   req = mySmartUpload.getRequest();//得到JspSmart中的Request对象,提取表单中其他数据
   String fileName = "";
   String fileExt = "";
   try {
    //mySmartUpload.setDeniedFilesList("reg,jsp,asp,php");
    mySmartUpload.upload();// 上传文件
    fils = mySmartUpload.getFiles();
    com.jspsmart.upload.File file = fils.getFile(0);
    if (!file.isMissing()) {
     System.out.println(file.getFileName());
     fileName = date.toLocaleString().replaceAll("-", "").replaceAll(":", "").replaceAll(" ", "");
     fileName += Double.toString(Math.random()).substring(2).substring(0,4);
     // 文件路径
     String sourceFile = "/upload/km_" + fileName + "."+ file.getFileExt();
     fileExt = file.getFileExt();
     // 保存源图
     file.saveAs(sourceFile, com.jspsmart.upload.File.SAVEAS_VIRTUAL);
    }
   } catch (SmartUploadException e) {
   
    out.write("失败");
    e.printStackTrace();
   }
   String WEBROOT = request.getRealPath("/");
    out.println(WEBROOT+"upload"+"//"+"km_"+ fileName+"."+fileExt+"");
          

   
}

猜你喜欢

转载自blog.csdn.net/ssdate/article/details/5686441
今日推荐