`
neil-jh
  • 浏览: 145973 次
  • 性别: Icon_minigender_1
  • 来自: 上海
文章分类
社区版块
存档分类
最新评论

上传文件

阅读更多
package com.derby.dms.neil;

import com.opensymphony.xwork2.ActionSupport;

import java.io.File;
import java.io.IOException;

public class UploadFileAction extends ActionSupport {

    private File[] file;
    private String[] fileName;
    private static final float CONSTANT = 1024f;
    private static final String[] TYPES = new String[]{"jpg,bmp,gif"};
    private int allowSize = 1;
    private static final String CONTANT_FILE_PATH = "d:/upload";

    private boolean checkFileSize(int allowSize) {
        if (fileName != null && fileName.length > 0) {
            for (int i = 0; i < fileName.length; i++) {
                Long size = new Long(Math.round(file[i].length() / CONSTANT));
                if (size > allowSize) {
                    return false;
                }
            }
        }
        return true;
    }

    public boolean checkFileType(String fileName) {
        boolean flat = false;
        for (String type : TYPES) {
            if (fileName.toLowerCase().endsWith(type)) {
                flat = true;
                break;
            }
        }

        if (!flat) {
            StringBuffer buf = new StringBuffer("文件类型必须为以下几种类型:");
            for (String type : TYPES) {
                buf.append(type);
                buf.append(",");
            }
            addActionError(buf.toString().substring(0, buf.length() - 1));
        }
        return flat;
    }

    public boolean uploadFile(File file, String fileName) {

        boolean flat = false;

        String[] newFileName = fileName.split("\\.");

        if (!checkFileSize(allowSize)) {
            return flat;
        }

        File newFilePath = new File(CONTANT_FILE_PATH);
        if (!newFilePath.exists()) {
            newFilePath.mkdir();
        }

        File newFile = new File(CONTANT_FILE_PATH + System.currentTimeMillis() + newFileName[fileName.length() - 1]);

        try {
            org.apache.commons.io.FileUtils.copyFile(file, newFile);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return flat;

    }

    public File[] getFile() {
        return file;
    }

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

    public String[] getFileName() {
        return fileName;
    }

    public void setFileName(String[] fileName) {
        this.fileName = fileName;
    }

    /*
    public static void main(String[] args) {
        
        int i = Math.round(5/2.5f);
        System.out.println(i);
    }
    */
}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics