Struts文件上传与下载详解 _上传多个文件
发布日期:2021-05-14 13:06:28 浏览次数:26 分类:精选文章

本文共 2799 字,大约阅读时间需要 9 分钟。

创建一个支持多文件上传的Struts应用程序是一项常见但稍微复杂的任务。对于经验丰富的开发人员来说,这并不是一个难以逾越的鸿沟,但对于初学者而言,可能需要一些步骤来理清思路。本文将详细介绍如何实现一个能够支持多个文件上传的Struts应用程序。

1. 创建JSP表单页面

首先,我们需要创建一个JSP表单页面,这个页面将包含支持多个文件上传的表单。以下是需要使用的Struts标签:

多文件上传
文件上传

请注意上面代码中有一些注释(如<!-- 这些代码被注掉了 -->),这些注释是为了表达原本想要实现的功能,但在代码中被注掉了。请确保在实际使用前,这些注释被正确移除或替换。

2. 实现UploadAction类

接下来,我们需要编写UploadAction类,用于处理文件上传逻辑。以下是一个示例代码:

package org.web;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class UploadAction extends ActionSupport {
private File[] mupload;
private String[] muploadContentType;
private String[] muploadFileName;
private String msavePath;
public String execute() throws IOException {
byte[] buffer = new byte[1024];
for (int i = 0; i < mupload.length; i++) {
String path = ServletActionContext.getServletContext().getRealPath(msavePath);
File upFile = mupload[i];
String fileName = muploadFileName[i];
File file = new File(path, fileName);
if (!file.isDirectory()) {
File parentDir = file.getParentFile();
if (!parentDir.exists()) {
parentDir.mkdirs();
}
}
FileInputStream fis = new FileInputStream(upFile);
FileOutputStream fos = new FileOutputStream(file);
int length = 0;
while ((length = fis.read(buffer)) > 0) {
fos.write(buffer, 0, length);
}
fis.close();
fos.flush();
fos.close();
}
return SUCCESS;
}
public File[] getMupload() {
return mupload;
}
public void setMupload(File[] mupload) {
this.mupload = mupload;
}
public String[] getMuploadFileName() {
return muploadFileName;
}
public void setMuploadFileName(String[] muploadFileName) {
this.muploadFileName = muploadFileName;
}
public String getMsavePath() {
return msavePath;
}
public void setMsavePath(String msavePath) {
this.msavePath = msavePath;
}
}

3. 配置Struts配置文件

最后,我们需要在Struts配置文件中添加Action配置,以指示如何处理提交的数据。

/upload
/upload_suc.jsp

4. 最后一步:运行测试

完成以上步骤后,按照以下方式运行应用程序以测试多文件上传功能:

  • 将JSP页面copypaste到适当的位置。
  • 配置好Server和_struts配置文件。
  • 打开浏览器访问投放页面。
  • 上传多个文件,确保文件被正确保存到指定路径。
  • 通过以上步骤,您应该能够成功实现一个支持多文件上传的Struts应用程序。如果在过程中遇到问题,请在评论区留言,我会尽力协助解决!

    上一篇:Struts文件上传与下载详解_文件的下载
    下一篇:Struts文件上传与下载详解_上传单个文件

    发表评论

    最新留言

    很好
    [***.229.124.182]2025年04月09日 13时03分37秒