【问题标题】:How to find the extension of uploaded file in java?如何在java中找到上传文件的扩展名?
【发布时间】:2013-02-10 03:13:57
【问题描述】:

我有以下代码来上传文件,当我使用file.getNeme 时,它显示具有tmp 扩展名的临时文件名,我怎样才能找到实际上传文件的扩展名?我上传的文件名为test.jpg

import java.io.File;
import org.apache.commons.io.FileUtils;

public class FileUploder {

  private File file;

  public File getFile() {
        return file;
  }

  public void setFile(File file) {
        this.file = file;
  }
   ......

  System.out.println("file:" +file.getName());  
  try {
        File fileToCreate = new File(filePath,name);
        FileUtils.copyFile(file, fileToCreate);
  } catch (IOException ex) {
        ex.printStackTrace();
  }

  ......

当前输出类似于 >>> file:upload__1a6d32_13d0eda6d49__7fdf_00000012.tmp

【问题讨论】:

标签: java struts2 upload


【解决方案1】:

只需添加另一个 getter/setter,如下所示,并删除 getFile() 方法,它就会起作用

私有字符串文件文件名;

public String getFileFileName() {
    return fileFileName;
}

public void setFileFileName(String fileFileName) {
    this.fileFileName = fileFileName;
}

【讨论】:

    【解决方案2】:
       private String getImageFileExtendtion (FileItem item) {
            String formatName = "png";
            String fileName = item.getName();
            if (fileName != null && fileName.length() >0) {
                int index = -1;
                 for (int i = fileName.length()-1 ; i >=0; i --) {
                     if (fileName.charAt(i)=='.') {
                         index = i;
                         break;
                     }
                 }
                if (index >=0 && index < fileName.length() -1) {
                     formatName = fileName.substring(index+1);
                }
            }
            return formatName ;
        }
    

    【讨论】:

      【解决方案3】:

      你不应该使用file.getName()

      http://struts.apache.org/release/2.0.x/docs/file-upload.html#FileUpload-BasicUsage

      setX(File file)  
          The file that contains the content of the uploaded file. This is a temporary file and file.getName() will not return the original name of the file
      

      相反,创建另一个 setter setFileName(String fileName) 应该这样做。

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-12-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多