您的位置:首页 > 编程语言 > Java开发

Struts文件上传--2.多文件上传

2017-02-27 22:07 316 查看

.多文件上传

步骤如下:

(1)将commons-io-x.x.x.jar包和commons-fileupload-x.x.x.jar包导入到项目的WEB-INF/lib目录下;

(2)把form表单的enctype类型设为multipart/form-data,如下:

<form action="${pageContext.request.contextPath}/uploadImage.do" method="post" enctype="multipart/form-data">
<input type="file" name="image"/><br>
<input type="file" name="image"/><br>
<input type="submit" value="submit"/>
</form>

(3)在Action类中添加以下属性:

         1)File[] filename:文件名要和表单中提交的name属性相同;

         2)String[] filenameContentType:得到文件的类型(文件名+ContentType是固定格式);

         3)String[] filenameFileName:得到文件的名称(文件名+FileName是固定格式)。

Action类中需要使用FileUtils.copyFile(srcFile,destFile),用来复制上传的文件到项目中。

示例如下:

struts.xml中关键代码:

<action name="uploadImage" class="com.chen.action.SubmitForm" method="upload">
<!-- 为Action的 imagePath属性注入值-->
<param name="imagePath">/images</param>
<result name="success">/sayMessage.jsp</result>
<result name="error">/sayMessage.jsp</result>
</action>

Action类的代码:

public class SubmitForm {
//返回信息
public String message=null;
//设置上传文件的保存文件路径
public String imagePath=null;
//文件
private File[] image;
//文件类型
private String[] imageContentType;
//文件名
private String[] imageFileName;
public String upload(){
//获取真实路径
String realPath=ServletActionContext.getServletContext().getRealPath(imagePath);
File file=new File(realPath);
if(!file.exists()){
file.mkdirs();
}
try {
for(int i=0;i<image.length;i++){
FileUtils.copyFile(image[i], new File(file,imageFileName[i]));
}
message="save OK";
return "success";
} catch (IOException e) {
message="save error";
return "error";
}
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getImagePath() {
return imagePath;
}
public void setImagePath(String imagePath) {
this.imagePath = imagePath;
}
public File[] getImage() {
return image;
}
public void setImage(File[] image) {
this.image = image;
}
public String[] getImageContentType() {
return imageContentType;
}
public void setImageContentType(String[] imageContentType) {
this.imageContentType = imageContentType;
}
public String[] getImageFileName() {
return imageFileName;
}
public void setImageFileName(String[] imageFileName) {
this.imageFileName = imageFileName;
}
}

注:通过Struts的常量可以配置上传文件的大小。

<constant  name="struts.multipart.maxSize"  
value="10701096"/>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息