/多文件上传
public ActionForward multipartFileUpload(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
//转换为自己的表单,这里只要经过了一个表单就可以 ,不管里面的内容
MulForm form2 = (MulForm)form;
//多文件上传,通过form来获得页面的input = file的元素
//用一个Hashtable来接收,<String,FormFile> ----键是页面的<input type="file" name="key">里面的name属性
Hashtable<String, FormFile> hashtable = form2.getMultipartRequestHandler().getFileElements();
//因为我在struts-config.xml里面控制了上传文件的大小
//当文件超过了大小的时候,hashtable里面是空的,所以在这里判断一下
if(hashtable.size()==0){
request.setAttribute("info", "文件太大了!");
}else {
//循环里面的file
for (Entry<String, FormFile> entry : hashtable.entrySet()) {
//如果是没有上传文件,是空的要判断一下,用名字的长度来判断
if(entry.getValue().getFileName().length()!=0){
//获得保存路径
String fileName = entry.getValue().getFileName();
String webPath = ConfigPath.getProp().getProperty(ConfigPath.propKey);
String realPath = this.getServlet().getServletContext().getRealPath(webPath);
String savePath = ConfigPath.getSavePath(fileName, realPath);
//建立流的管道
InputStream inStream = entry.getValue().getInputStream();
OutputStream outStream = new FileOutputStream(savePath);
//开始传
int len = 0 ;
byte[] b = new byte[1024];
while ((len = inStream.read(b))!=-1) {
outStream.write(b, 0, len);
}
outStream.close();
inStream.close();
}
}
request.setAttribute("info", "上传成功!");
}
return mapping.findForward("showInfo");
}
================================
public class ConfigPath {
public static final String propKey = "hwt.MultipartUpload.relativePath";
private static Properties prop = null ;
private ConfigPath(){}
static{
prop = new Properties();
//配置文件要放在类文件目录下面
InputStream inStream = ConfigPath.class.getResourceAsStream("/configPath.properties");
try {
prop.load(inStream);
} catch (IOException e) {
e.printStackTrace();
}
}
//处理文件上传的目录和文件名
public static String getSavePath(String fileName,String realPath){
//把文件名改成唯一的文件名 用UUID
UUID uuid = UUID.randomUUID();
String extraName = fileName.substring(fileName.lastIndexOf("."));
String uniqueFileName = uuid+extraName;
//文件的存储目录
Calendar calendar = new GregorianCalendar();
//===注意这里的盘符啊,在java中有盘符的绝对路径的时候要\\,因为编译器不认识\ 要转移\\
//==相对路径就用这个/
String path = realPath+"\\"+calendar.get(Calendar.YEAR)+"\\"+calendar.get(Calendar.MONTH)+
"\\"+calendar.get(Calendar.DATE);
//不要忘了要创建不存在目录的时候
File file = new File(path);
if(!file.exists()){
file.mkdirs();
}
return path+"\\"+uniqueFileName;
}
//返回配置文件
public static Properties getProp(){
return prop;
}
}
多文件上传
最新推荐文章于 2022-09-06 11:29:58 发布