index.jsp:
<%@page pageEncoding="utf-8"%>
<h1>利用smartUpload实现文件上传</h1><hr>
<center>
<form method="POST" action="myuploader"
ENCTYPE="multipart/form-data" >
名 称: <input type="text" name="name"><p>
缩略图片: <input type="file" name="file1" ><p>
标准图片: <input type="file" name="file2" ><p>
<input type=submit value="提 交"> <input type=reset value="重 置">
</form>
</center>
<%
if(request.getAttribute("msg")!=null)
out.println("<script>alert(' "+request.getAttribute("msg")+" ' )</script>");
%>
servlet:
package com.zuidaima.smartupload.demo;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.text.SimpleDateFormat;
import java.util.*;
import com.jspsmart.upload.*;
public class MyUploader extends HttpServlet {
ServletConfig config;
public void init(ServletConfig config) throws ServletException {
super.init(config);//初始化servlet,主要目的是得到初始化信息
//将得到的config保存为成员变量,目的是下一步使用
this.config = config;
}
public void doPost(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
String msg="";
SmartUpload uploader = new SmartUpload();
try {
uploader.initialize(config, request, response);// 初始化上载器
uploader.upload(); // 上载表单数据
// 此时才能读取表单数据
Enumeration<?> e = uploader.getRequest().getParameterNames();
while (e.hasMoreElements()) { //遍历所有表单参数(不包括文件)
String key = (String) e.nextElement();
if ("name".equals(key)) { //找到需要的参数
//不能用request.getParameter(),只能用下列语句获取参数值
String name = uploader.getRequest().getParameterValues(key)[0];
}
}
for (int i = 0; i < uploader.getFiles().getCount(); i++) {
com.jspsmart.upload.File myFile = uploader.getFiles().getFile(i);
if (!myFile.isMissing()) { //文件上传成功
String fileName = "/upload/"+
new SimpleDateFormat("yyyyMMdd").format(new Date())+
(int) (Math.random() * 90+10)+"."+myFile.getFileExt();
myFile.saveAs(fileName, uploader.SAVE_VIRTUAL);
} //上一行为提示信息
}
msg="上传成功,共上传"+uploader.getFiles().getCount()+"个文件.";
} catch (SmartUploadException e) {
msg=e.getMessage(); //将出错信息以提示信息形式显示
e.printStackTrace();
}
request.setAttribute("msg",msg); //存储提示信息
request.getRequestDispatcher("index.jsp").forward(request, response);
return;
}