67,513
社区成员
发帖
与我相关
我的任务
分享
java多文件上传(通过commos包中的DiskFileUpload的类来重新封装请求)
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {
// TODO Auto-generated method stub
/*
* PicForm pForm=(PicForm)form; FormFile file=pForm.getFile();
* //获取上传的绝对路径 String
* path=this.getServlet().getServletContext().getRealPath("/upload");
* //获取文件名 String
* filename=System.currentTimeMillis()+file.getFileName(); //上传的绝对路径
* String filepath=path+"/"+filename; try { FileOutputStream fos=new
* FileOutputStream(filepath); fos.write(file.getFileData());
* fos.flush(); fos.close(); System.out.println("上传成功"); } catch
* (Exception e) { // TODO: handle exception }
*/
try {
String dir = servlet.getServletContext().getRealPath("/upload");
// String path = this.getServlet().getServletContext().getRealPath(
// "/img");
DiskFileUpload dfu = new DiskFileUpload();
// 设置上传数据的最大大小为10M。
dfu.setSizeMax(0xA00000);
// 设置内存缓冲区的阀值为512K。
dfu.setSizeThreshold(0x80000);
// 设置临时存储文件的目录为E:\fileupload。
dfu.setRepositoryPath("E:\\fileupload");
// 得到FileItem对象的列表。
List fileItems = null;
fileItems = dfu.parseRequest(request);
Iterator it = fileItems.iterator();
while (it.hasNext()) {
FileItem item = (FileItem) it.next();
String filename = new String(item.getName().getBytes(
"ISO8859-1"), "utf-8");
// System.out.println(item.getName() + item.getContentType()
// + item.getFieldName());
System.out.println(item.getContentType());
System.out.println(filename.substring(filename.lastIndexOf(".")));
String filepath = dir + "/" + filename.substring(filename.lastIndexOf("\\"));
item.write(new File(filepath));
System.out.println("success");
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
//使用列表来接收上传文件
private List<File> uploadFile;
private List<String> uploadFileContentType;
private List<String> uploadFileFileName;
//getter和setter方法省略,注意文件命名的规则 uploadFile和标签中的name对应
//上传
if (fileCount > 0) {
for (int i = 0; i < uploadFile.size(); i++) {
if (null != uploadFileFileName.get(i) && uploadFileFileName.get(i).trim().length() > 0) {
ai = new ActivityImage();
String tempFileName = CommonUtils.reName(uploadFileFileName.get(i));
String dir = ServletActionContext.getServletContext().getRealPath("/upload/activity");
File dirs = new File(dir);
if (!dirs.exists()) {
dirs.mkdir();
}
String picturePath = dir + "/" + tempFileName;
File imageFile = new File(picturePath);
try {
//这里进行IO操作,拷贝文件流,你自己完成就行了
} catch (Exception e) {
e.printStackTrace();
}
}
}
}