java
package com.ljr.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.lxh.smart.File;
import org.lxh.smart.SmartUpload;
import org.lxh.smart.SmartUploadException;
public class UploadServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
request.setCharacterEncoding("utf-8");
try {
SmartUpload su = new SmartUpload();
su.initialize(this.getServletConfig(),request,response);
su.setMaxFileSize(1024*1024);
su.setTotalMaxFileSize(9*1024*1024);
su.upload();
int count=0;
for(int i=0;i<su.getFiles().getCount();i++){
File file = su.getFiles().getFile(i);
if(file.isMissing()){
continue;
}
//重命名文件名
count++;
DateFormat dtf = new SimpleDateFormat("yyyyMMddHHmmss");
String date = dtf.format(new Date());
Random random = new Random();
String rand = "";
for(int j=0;j<3;j++){
rand = rand+random.nextInt(10)+"";
}
String fileSaveName = date + rand+i;
System.out.println(fileSaveName);
//存储路径(upload为项目中已经创建的文件夹)
file.saveAs("/upload/"+fileSaveName+"."+file.getFileExt());
//存储的路径(存入数据库的url)
String url = "upload/"+fileSaveName+"."+file.getFileExt();
System.out.println(url);
request.getRequestDispatcher("./index.jsp").forward(request, response);
}
} catch (SmartUploadException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
out.flush();
out.close();
}
}
jsp页面
<form action="uploadServlet" method="post" enctype="multipart/form-data">
<input type="file" id="file" name="file"/><input type="submit" value="上传">
</form>