commons-fileupload 小结

最近写上传文件,用到了这个东西,我想很多人对这个并不陌生。
下面贴出代码。
commons-fileupload 在struts1.x中的应用方法

DynaActionForm uf = (DynaActionForm) form;
FormFile file = (FormFile) uf.get("file");

System.out.println(file.getFileName());
String trackno=request.getParameter("trackno");

SimpleDateFormat myFmt=new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss");
String fileName= "temp"+myFmt.format(new Date()) +".xls";
String realPath ="";
realPath = uploadRootPath + File.separator + fileName;
FileOutputStream fout = null;
fout = new FileOutputStream(realPath);
fout.write(file.getFileData());
fout.flush();
fout.close();

在springMVC中

Iterator<FileItem> itr = fileItems.iterator();




Map<String, Object> map = new HashMap<String, Object>();
while (itr.hasNext()) {// 依次处理每个文件


FileItem item = (FileItem) itr.next();
String fileName = item.getName();// 获得文件名,包括路径
if(!item.isFormField()){



if (!"".equals(fileName)) {


File fullFile = new File(item.getName());
File savedFile = new File(savePath, fullFile.getName());
try {
item.write(savedFile);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
}else{
if("title".equals(item.getFieldName())){
title = new String(item.getString().getBytes("ISO-8859-1"),"UTF-8");

}
if("kinds".equals(item.getFieldName())){
String category1=new String(item.getString().getBytes("ISO-8859-1"),"UTF-8");

categoryList.add(category1);

}
if("content".equals(item.getFieldName())){
content=new String(item.getString().getBytes("ISO-8859-1"),"UTF-8");

}
}

}

}


如果单独使用的话,如果想获取表单中其他信息 需要判断,才可以

spring上传文件方式:
	Iterator<String> it = multiRequest.getFileNames();
while(it.hasNext()){
String key=it.next();
MultipartFile file = multiRequest.getFile(key);
String filename=RandomStringUtils.randomNumeric(10)+file.getOriginalFilename();



//fileUploadHelper.SaveFileFromInputStream(file.getInputStream(), savePath, filename);

final File targetFile = new File(savePath + File.separator + fileName);
file.transferTo(targetFile);

此处是一个多文件上。单文件都可以

和所有新手一起分享下
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值