Strut2学习笔记(2) - 简单的文件上传系统

简单的文件上传系统

1.编写FileAdd.jsp -(View)

<%@ page language="JAVA" contentType="TEXT/HTML; charset=UTF-8" pageEncoding="UTF-8" %>
<%@ taglib prefix="s" uri="/struts-tags" %>

...

<body>
<h4>Add File<h4>

<! enctype必须为multipart/form-data,该属性告诉框架这个请求需要被当做上传处理 >
<s:form action="FileUploader" method="post" enctype="multipart/form-data" >
<s:file name="file" label="FileName" />
<s:submit />
</s:form>
</body>

...


2.编写FileUploader.java -(Model)

public class FileUploader {

//上传文件方法
public void FileUpload(File file, String fileName, String DestinationPath) {
FileInputStream in;
FileOutputStream out;

File dir = new File(DestinationPath); //将给定路径名字符串转换为抽象路径名来创建一个新 File 实例,此File表示路径
if (!dir.exists()) {
dir.mkdir(); //按DestinationPath创建一个文件夹
}

//创建一个绝对路径targetPath
String targetPath = dir.getPath() + dir.separator + fileName;
File targetFile = new File(targetPath);

//上传文件
try {
in = new FileInputStream(file);
out = new FileOutputStream(targetFile);
int c;

while ((c = in.read()) != -1) {
out.write(c);
}
} finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}


3.编写FileUploaderAction.java -(Model)

public class FileUploaderAction extends ActionSupport {
public String excute() {
private fu = new FileUploader();

try {
fu.FileUpload(getFile(), getFileName(), destinationPath);
} catch (Exception ex) {
ex.printStack();
}

return SUCCESS;
}

private File file;
private String fileName;
private String destinationPath;

... /* 各成员变量的getter及setter */

}


4.配置sturts.xml

<struts>
<constant name="struts.devMode" value="true" />
<package name="Upload" extends="struts-default" >
<action name="FileAdd" >
<result>/FileAdd.jsp</result>
</action>

<action name="FileUploader" class="com.vea.FileUploaderAction" >
<param name="destinationPath">./UploadFolder/</param>
<result>/FileAdded.jsp</result>
<result name="INPUT">/FileAdd.jsp</result>
</action>
</package>
</struts>


5.配置欢迎页面 index.jsp -(View)
加入如下语句
<meta http-equiv="REFRESH" content="1;URL=FileAdd.action" />
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值