解决Struts2上传文件到tomcat,重启tomcat后 ,文件自动被删除。

来源:互联网 发布:网络剧如何盈利 编辑:程序博客网 时间:2024/09/15 11:02

网上看了一大堆的文章,试了都没有效果。后面自己慢慢摸索,找到了解决办法。只要使用FileUtils.copyFile(File a,File b), 而不是使用自己写文件输入输出流。便可以解决问题。上传文件,即使重启tomcat,文件还要保留,不被删除。话不多说,先贴代码。

Action代码

package com.action;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.io.PrintWriter;import java.text.SimpleDateFormat;import java.util.Arrays;import java.util.Date;import java.util.HashMap;import java.util.List;import java.util.Random;import org.apache.commons.io.FileUtils;import org.apache.struts2.ServletActionContext;import org.json.simple.JSONObject;public class upload extends BaseAction {//附件表需要url(路径+文件名)和文件名两个值private List<File> file;//文件名private List<String> fileFileName;private List<String> fileContentType;//Url+文件名// private String saveUrl;public List<File> getFile() {return file;}public void setFile(List<File> file) {this.file = file;}public List<String> getFileFileName() {return fileFileName;}public void setFileFileName(List<String> fileFileName) {this.fileFileName = fileFileName;}public List<String> getFileContentType() {return fileContentType;}public void setFileContentType(List<String> fileContentType) {this.fileContentType = fileContentType;}public String upload() throws Exception{for(int i=0;i<file.size();i++){// InputStream is=new FileInputStream(file.get(i));    ServletActionContext.getResponse().setContentType(                 "text/html; charset=UTF-8");         // 文件保存目录路径 (相对路径)        String savePath = ServletActionContext.getServletContext().getRealPath(    "/")   + "upload/";         System.out.println("savePath:"+savePath);       // 文件保存目录URL  (相对路径)        String saveUrl = ServletActionContext.getRequest().getContextPath()  + "/upload/";             //绝对路径//     String savePath="D:\"EclipseWorkspace\"mqs\"upload\"";//     String saveUrl="D:\"EclipseWorkspace\"mqs\"upload\"";                    PrintWriter out = null;         try {             out = ServletActionContext.getResponse().getWriter();         } catch (IOException e1) {          }                // 检查目录         File uploadDir = new File(savePath);         if (!uploadDir.isDirectory()) {             out.println(getError("上传目录不存在。"));             return null;         }         // 检查目录写权限         if (!uploadDir.canWrite()) {             out.println(getError("上传目录没有写权限。"));             return null;         }  //        System.out.println("dir》》》savePath2:"+savePath);//        System.out.println("dir>>>>>saveUrl2:"+saveUrl);       File saveDirFile = new File(savePath);         if (!saveDirFile.exists()) {              saveDirFile.mkdirs();         }          // 创建文件夹         SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");         String ymd = sdf.format(new Date());         savePath += ymd + "/";         //(用于保存数据库的url)       saveUrl += ymd + "/";  //        System.out.println("savePath2:"+savePath);//        System.out.println("saveUrl2:"+saveUrl);       File dirFile = new File(savePath);         if (!dirFile.exists()) {             dirFile.mkdirs();         }                //fileFileName.get(i) 是存入数据库的文件名       //saveUrl+fileFileName.get(i)是存入数据库的url       File uploadedFile = new File(savePath, fileFileName.get(i));         //       System.out.println(saveUrl+fileFileName.get(i));       try {             FileUtils.copyFile(file.get(i), uploadedFile);             JSONObject obj = new JSONObject();             obj.put("error", 0);             obj.put("url", saveUrl + fileFileName.get(i));              out.println(obj.toString());          } catch (Exception e) {          }  File destFile =new File(savePath,this.getFileFileName().get(i));FileUtils.copyFile(file.get(i), uploadedFile);  // OutputStream os =new FileOutputStream(destFile);// byte[] buffer=new byte[1024];// int length=0;// while ((length=is.read(buffer))>0){// os.write(buffer,0,length);// }// is.close();// os.close();}return SUCCESS;}  private String getError(String message) {         JSONObject obj = new JSONObject();         obj.put("error", 1);         obj.put("message", message);          return obj.toString();     }  }


Struts.xml代码

<action name="upload" class="com.action.upload" method="upload"><result name="success">/kindeditor/jsp/ok.jsp</result></action>


Jsp代码 upload.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%@ taglib prefix="s" uri="/struts-tags"  %><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>    <base href="<%=basePath%>">        <title></title>    <meta http-equiv="pragma" content="no-cache"><meta http-equiv="cache-control" content="no-cache"><meta http-equiv="expires" content="0">    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"><meta http-equiv="description" content="This is my page"><!--<link rel="stylesheet" type="text/css" href="styles.css">-->  </head>    <body>     <s:form action="upload" enctype="multipart/form-data" method="post">    <s:file name="file" label="请选择文件上传"></s:file>      <s:file name="file" label="请选择文件上传"></s:file>    <s:submit value="submit" label="submit"></s:submit>        </s:form>  </body></html>


上传成功后显示文件名的文件 ok.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%@ taglib prefix="s" uri="/struts-tags"  %><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>    <base href="<%=basePath%>">        <title></title>    <meta http-equiv="pragma" content="no-cache"><meta http-equiv="cache-control" content="no-cache"><meta http-equiv="expires" content="0">    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"><meta http-equiv="description" content="This is my page"><!--<link rel="stylesheet" type="text/css" href="styles.css">-->  </head>    <body>  File Name:<s:property value="fileFileName"/>  </body></html>


0 0
原创粉丝点击