package com.bdqn.zhp.util;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.ServletConfig;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.jspsmart.upload.File;
import com.jspsmart.upload.Request;
import com.jspsmart.upload.SmartUpload;
public class MyUpload {
private Request request;
private String fileName;
private String[] fileNames;
private SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmssSSS");
private static int count;
public int getCount(){
count++;
if(count>=1000){
count=0;
}
return count;
}
public void upload(ServletConfig config,HttpServletRequest request,HttpServletResponse response){
try {
//文件上传
SmartUpload su = new SmartUpload();
// su.setMaxFileSize(1000);
su.initialize(config, request, response);
su.setMaxFileSize(1024);
su.setAllowedFilesList("PNG,png");//只允许上传的文件类型
su.upload();
this.request = su.getRequest();
File file = su.getFiles().getFile(0);
//获取客户端选择文件名称
// fileName = file.getFileName();
//文件重命名
String ext = file.getFileExt();///获取文件原有扩展名
// saveFileName = System.currentTimeMillis()+"."+ext;
fileName = format.format(new Date())+getCount()+"."+ext;
//文件另存为 到upload文件夹中
file.saveAs("upload/"+fileName);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 多文件上传
* @param config
* @param request
* @param response
*/
public void uploads(ServletConfig config,HttpServletRequest request,HttpServletResponse response){
try {
//文件上传
SmartUpload su = new SmartUpload();
su.initialize(config, request, response);
su.upload();
this.request = su.getRequest();
//获取文件个数
int count = su.getFiles().getCount();
fileNames = new String[count];
for(int i=0;i<count;i++){
File file = su.getFiles().getFile(i);
//文件重命名
String ext = file.getFileExt();///获取文件原有扩展名
fileNames[i] = format.format(new Date())+getCount()+"."+ext;
//文件另存为 到upload文件夹中
file.saveAs("upload/"+fileNames[i]);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public Request getRequest(){
return request;
}
public String getFileName(){
return fileName;
}
public String[] getFileNames() {
return fileNames;
}
public void setFileNames(String[] fileNames) {
this.fileNames = fileNames;
}
}