---
title: "JavaScript+Struts2实现可选择性多文件上传"
author: "ducklsl"
date: "2013-04-05T14:09:04Z"
tags: ["Java", "Struts"]
categories: ["编程语言"]
slug: "javascript-struts2"
draft: false
lastmod: "2013-04-07T23:04:17Z"
id: 1842227
url: "https://changluo.iteye.com/blog/1842227"
---

页面代码： \[code="html"] My JSP 'index.jsp' starting page

file

\[/code]当多文件上传时，在Struts2的Action类中可以使用数组也可以使用List泛型的方式来获取上传的多文件，获取数组后，处理方式就和单个文件上传的方式一样 Action处理代码： \[code="java"]private File\[] upload; // 上传的文件，与页面的中的name属性一致 private String\[] uploadFileName;// 文件名，Struts规定个格式 \[name]FileName private String\[] uploadContentType;// 文件类型，Struts规定的格式\[name]ContentType @SuppressWarnings("deprecation") public String execute() { try { for (int i = 0; i &lt; upload.length; i++) { InputStream is = new FileInputStream(upload\[i]);// 创建输入流，读取上传文件 // String parentDir = // ServletActionContext.getServletContext().getRealPath(parentDir); String parentDir = ServletActionContext.getRequest() .getRealPath("/upload");// 指定文件上传目录 File destFile = new File(parentDir, this.getUploadFileName()\[i]); if (!destFile.getParentFile().exists()) {// 判断存放文件的目录是否存在 destFile.getParentFile().mkdir();// 不存在则创建 } OutputStream os = new FileOutputStream(destFile);// 创建输出流，将内容写入文件 byte\[] buffer = new byte\[1024]; int length = 0; while ((length = is.read(buffer)) &gt; 0) {// 读文件 os.write(buffer, 0, length);// 写文件 } is.close();// 关闭inputStream os.close();// 关闭outputStream } } catch (Exception e) { e.printStackTrace(); } return "success"; }\[/code] 也可以使用泛型的方式进行接收，并且处理： \[code="java"]private List upload; //上传的文件，与页面的中的name属性一致 private List uploadFileName;//文件名，Struts规定个格式 \[name]FileName private List uploadContentType;//文件类型，Struts规定的格式\[name]ContentType @SuppressWarnings("deprecation") public String execute() { try { for(int i=0;i 0) {// 读文件 os.write(buffer, 0, length);// 写文件 } is.close();//关闭inputStream os.close();//关闭outputStream } } catch (Exception e) { e.printStackTrace(); } return "success"; }\[/code]只是对多个文件进行遍历，而处理的方式和单个文件是一致的