文件上传

 

1.上传的步骤:

  a.导入SmartUpload.jar

  b.创建一个上传的类的对象

  c.初始化

  d.上传至服务器

  e.保存

表单提交时需要指定enctype="multipart/form-data"(多数据类型提交)

 http://www.atguigu.com/opensource.shtml#3(包下载地址)

package com.zuxia.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jspsmart.upload.SmartUpload;
import com.jspsmart.upload.SmartUploadException;

/**

*文件上传

*/

public class UploadServlet extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
      this.doPost(request, response);
    }
    public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
      //创建一个上传/下载的类的对象
      SmartUpload su = new SmartUpload();
      //初始化对象
      su.initialize(getServletConfig(), request, response);
      try {
        //设置上传文件的信息(文件大小、文件类型)
        //设置允许上传的文件的类型
        su.setAllowedFilesList("txt,jpg,png,gif,mp3");
        //设置不允许上传的文件的类型
        su.setDeniedFilesList("exe");
        //设置文件上传的大小限制
        su.setMaxFileSize(1024*1024*2);//2M字节数
        //上传文件至服务器
        su.upload();
        //指定文件保存路径
        su.save("/files");
        System.out.println("上传成功!");
        response.sendRedirect("../show.jsp");
      } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
   }

}

 

 

/*index.jsp*/

 

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">

<title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>

<body>
<form action="servlet/UploadServlet" method="post" enctype="multipart/form-data">
<input type="file" name="myfile"/><br/><br/>
<input type="file" name="myfile"/><br/><br/>
<input type="file" name="myfile"/><br/><br/>
<input type="submit" value="上传"/>
</form>
</body>
</html>

posted @ 2017-07-10 22:18  知~味~  阅读(133)  评论(0编辑  收藏  举报