欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

(六)Servlet 文件上传(3)- smartupload 简单文件上传(转载)

最编程 2024-06-23 11:59:10
...
开源中国社区团队直播首秀,以分享为名讲述开源中国社区背后的故事”

创建工程后首先需要导入包

jsp-api.jar

jspsmartupload.jar

servlet-api.jar

 

将这三个包放入web-inf 下的lib中

然后就可以开始编写程序了

先是写一个表单的html,将form提交到action 的sevlet代码如下:

<!DOCTYPE html>  
<html>  
<head>  
<meta charset="UTF-8">  
<title>Insert title here</title>  
</head>  
<body>  
    <form action="action" method="post" enctype="multipart/form-data">  
        <input type = "file" name="file">  
        <input type = "file" name="file">  
        <input type="submit" value="提交">   
          
    </form>  
  
      
</body>  
</html>  

然后编写servlet

package com.test;  
  
import java.io.File;  
import java.io.IOException;  
  
import javax.servlet.ServletConfig;  
import javax.servlet.ServletException;  
import javax.servlet.annotation.WebServlet;  
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;  
  
/** 
 * Servlet implementation class action 
 */  
@WebServlet("/action")  
public class action extends HttpServlet {  
    private static final long serialVersionUID = 1L;  
  
         
    /** 
     * @see HttpServlet#HttpServlet() 
     */  
    public action() {  
        super();  
        // TODO Auto-generated constructor stub  
    }  
  
    /** 
     * @see Servlet#init(ServletConfig) 
     */  
  
  
    /** 
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) 
     */  
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  
        // TODO Auto-generated method stub  
        doPost(request, response);  
    }  
  
    /** 
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) 
     */  
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  
        // TODO Auto-generated method stub  
        SmartUpload smart = new SmartUpload();//新建servlet  
        smart.initialize(this.getServletConfig(), request, response);//初始化servlet  
        try {  
            smart.upload();//上传准备  
            String path="d:"+File.separator+"testDocument";  
            smart.save(path);//文件保存  
        } catch (SmartUploadException e) {  
            // TODO Auto-generated catch block  
            e.printStackTrace();  
        }  
    }  
  
}  

此外还有一些要注意的,因为封装了form表单,getparameter将取不到值,不过smartupload()提供了解决的方法

推荐阅读