Struts2保存文件到服务器指定目录。
Struts2中保存文件到服务器上时,可以使用
ServletActionContext.getServletContext().getRealPath("/");
获取服务器的根路径,然后再把想要的文件保存到具体的路径中。如下面的例子,把图片保存到服务器根目录下的images/user_photo/中,关于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(); }