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

[JavaWeb基础] 009.Struts2 上传文件

2015-07-26 23:19 549 查看
在web开发中,我们经常遇到要把文件上传下载的功能,这篇文章旨在指导大家完成文件上传功能

1.首先我们需要一个上传文件的页面。

<!--在进行文件上传时,表单提交方式一定要是post的方式,
因为文件上传时二进制文件可能会很大,还有就是enctype属性,
这个属性一定要写成multipart/form-data,
不然就会以二进制文本上传到服务器端
-->
<form action="fileUpload.action" method="post" enctype="multipart/form-data">
用户名: <input type="text" name="username"><br><br>
文件:    <input type="file" name="file"><br><br>
<input type="submit" value="提交">
</form>


2.然后我们要配置Struts2文件。

<action name="fileUpload" class="com.babybus.sdteam.action.FileUploadAction">
<result name="success">/Success.jsp</result>
</action>


3.最后我们要有一个Action类来把上传的文件转存到服务器

public String execute() throws Exception
{
// 设置要上传的文件夹目录
String root = ServletActionContext.getServletContext().getRealPath("/upload");
// 根据上传的文件,创建输入流
InputStream is = new FileInputStream(file);
// 输出文件夹
File outfloder = new File(root);
// 输出文件
File outfile   = new File(root, fileFileName);
// 目录不存在创建目录
if(!outfloder.exists()){
outfloder.mkdirs();
}
// 文件不存在创建文件
if(!outfile.exists()){
outfile.createNewFile();
}
// 创建输出流
OutputStream os = new FileOutputStream(outfile);

// 接受数据用的临时字节数组
byte[] buffer = new byte[500];
int length = 0;
// 遍历把内容写到输出文件中
while(-1 != (length = is.read(buffer, 0, buffer.length)))
{
os.write(buffer);
}
// 关闭输出流,关闭输入流
os.flush();
os.close();
is.close();
// 返回结果跳转标识
return SUCCESS;
}


4.通过以上几步,我们就可以简单的实现了文件上传功能。

结语

受益,掌握了Struts2 上传文件



本站文章为 宝宝巴士 SD.Team 原创,转载务必在明显处注明:(作者官方网站: 宝宝巴士 )

转载自【宝宝巴士SuperDo团队】 原文链接: /article/6669128.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: