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

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

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()提供了解决的方法

转载于:https://my.oschina.net/u/2321708/blog/742445

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值