1、jsp简单页面
<%@ page language="java" contentType="text/html; charset=utf-8"%>
<html>
<head>upload文件上传</head>
<body>
<%-- "<%=request.getContextPath()%>/UploadServlet"--%>
<form action="UploadDemo/UploadServlet" method="post" enctype="multipart/form-data">
文件描述:<input type="text" name="desc" size="20" maxlength="80">
文件名称:<input type="file" name="file" size="20" maxlength="80">
<input type="submit" value="上传">
</form>
</body>
</html>
2、UploadServlet
package UploadDemo;
import java.io.IOException;
import java.io.PrintWriter;
import javax.security.auth.message.callback.SecretKeyCallback.Request;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.jspsmart.upload.File;
import com.jspsmart.upload.SmartUpload;
/**
* Servlet implementation class UploadServlet
*/
public class UploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setCharacterEncoding("utf-8");
PrintWriter out=response.getWriter();
out.println("<html>");
out.println("<body>");
out.println("<hr>");
out.println("执行......");
SmartUpload mySmartUpload=new SmartUpload();
int count=0; //上传文件数量
try{
//初始化工作
System.out.println("执行中-----");
mySmartUpload.initialize(this.getServletConfig(),request,response);
//限制文件上传最大长度
mySmartUpload.setMaxFileSize(50*1024*1024);
//设置文件上传的文件,仅允许doc与txt文件
mySmartUpload.setAllowedFilesList("doc,txt");
mySmartUpload.upload();
//获得上传的文件
File myfile=mySmartUpload.getFiles().getFile(0);
//获得上传文件的名字
String filename=myfile.getFileName();
//保存文件的目录
count=mySmartUpload.save("F:\\");
//获得文件的描述信息
Request re =(Request) mySmartUpload.getRequest();
String desc=((ServletRequest) re).getParameter("desc");
out.println(count+"file uploaded.<br>");
out.println("file description:"+desc);
}catch(Exception e){
out.println("Unable to upload the file!!");
out.println("Error:"+e.toString());
}
out.println("</body>");
out.println("</html>");
}
}