加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

Struts2 上传文件主要代码

发布时间:2020-12-15 00:29:15 所属栏目:Java 来源:网络整理
导读:今天PHP站长网 52php.cn把收集自互联网的代码分享给大家,仅供参考。 public File file; //与页面上的 input file 标签的name 一样 public String name; /** * 上传文件公共方法 * @param url 地址 * @param ext 后缀名 *

以下代码由PHP站长网 52php.cn收集自互联网

现在PHP站长网小编把它分享给大家,仅供参考

public File file; //与页面上的 input file 标签的name 一样
 public String name;

 

/**
  * 上传文件公共方法
  * @param url 地址
  * @param ext 后缀名
  * @return 上传成功
  */
 public boolean file(String url,String ext) {
  response = getResponse();

  InputStream input = null;
  long time = System.currentTimeMillis();
  OutputStream os = null;
  try {
   System.out.println(name);
   SystemParameter systemParameter = (SystemParameter) getRequest()
     .getSession().getServletContext()
     .getAttribute("systemParameter");
   String path = systemParameter.getFilePath() + url ;
   String houzui = name.substring(name.lastIndexOf("("),name.length());
   if (houzui.equals("(空白)")) {
    name=name.substring(0,name.indexOf("("));
   }
   if (name.equals("流程图")) {
    name="liuchen";
   }
   // 检查文件是否存在
   File f = new File(path,name+ ext);
   if (f.exists()) {
    System.out.println(f.getAbsolutePath());
    System.out.println(f.getName());
    String newName = path + name + "old_" + time
      + ext;

    System.out.println(newName);
    boolean is = f.renameTo(new File(newName));
    if (is == false) {
     f.renameTo(new File(path + name + ext));
    
     return false;
    } else {
     // 如果存在,在读一次改过文件的名字,如果新的名字不存在,就提示上传失败
     File file = new File(newName);
     if (!file.exists()) {
      return false;
     }
    }
   }
   input = new FileInputStream(file);

   os = new FileOutputStream(f);
   byte[] by = new byte[1024];
   int length = input.read(by);
   while (length != -1) {
    os.write(by,length);
    length = input.read(by);
   }
   return true;
  } catch (Exception e) {
   // TODO: handle exception
   e.printStackTrace();
  } finally {
   try {
    if (input != null)
     input.close();
    if (os != null)
     os.close();
  } catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  }

以上内容由PHP站长网【52php.cn】收集整理供大家参考研究

如果以上内容对您有帮助,欢迎收藏、点赞、推荐、分享。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读