Struts2保存文件到服务器指定目录

发布于 2011-06-05 | 更新于 2020-09-20

Struts2中保存文件到服务器上时,可以使用

ServletActionContext.getServletContext().getRealPath(“/”);

获取服务器的根路径,然后再把想要的文件保存到具体的路径中。如下面的例子,把图片保存到服务器根目录下的images/user_photo/中,关于Struts2上传多个文件的详细的例子可以参考这篇文章:

Struts2的一个和多个文件上传的实现

以下是Action中execute()方法保存图片的代码:

for (int i = 0; i < uploadFileName.size(); i++) {
Random random = new Random();
filename = (String) uploadFileName.get(i);
//保存到服务器的具体位置
String uploadPath=“images/user_photo/”;
//把上传的文件用生成的随机数重新命名
//并判断生成的文件名是否已经存在
//如果存在,则继续生成随机数命名,直到找打还没使用的随机数为止
filename = uploadPath + random.nextLong()
+ filename.substring(filename.lastIndexOf(“.”));
while (new File(filename).exists()) {
filename = uploadPath + random.nextLong()
+ filename.substring(filename.lastIndexOf(“.”));
}
//获取服务器的根目录
FileOutputStream fos = new FileOutputStream(ServletActionContext.getServletContext().getRealPath(“/”)+filename);
InputStream is = new FileInputStream(upload.get(i));
byte[] buffer = new byte[8192];
int count = 0;
while ((count = is.read(buffer)) > 0) {
fos.write(buffer, 0, count);
}
fos.close();
is.close();
}

本文作者: arthinking

本文链接: https://www.itzhai.comstruts2-specified-directory-to-save-the-file-to-the-server.html

版权声明: 版权归作者所有,未经许可不得转载,侵权必究!联系作者请加公众号。

×
IT宅

关注公众号及时获取网站内容更新。

请帅旋喝一杯咖啡

咖啡=电量,给帅旋充杯咖啡,他会满电写代码!

IT宅

关注公众号及时获取网站内容更新。