(六)Servlet文件上傳(3)--smartupload簡單文件上傳(轉載)

建立工程後首先須要導入包html

jsp-api.jarjava

jspsmartupload.jarweb

servlet-api.jarapi

 

將這三個包放入web-inf 下的lib中jsp

而後就能夠開始編寫程序了post

先是寫一個表單的html,將form提交到action 的sevlet代碼以下:this

<!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>  

而後編寫servletspa

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()提供瞭解決的方法code

相關文章
相關標籤/搜索