`
lucky_god
  • 浏览: 38387 次
社区版块
存档分类
最新评论

java apache common-io上传大文件报错

    博客分类:
  • java
阅读更多

 

我在用apache common-io jar包作影片上传时,发现大文件上传出错,以此博客作为笔记。调试并研究后发现,导致问题的原因是 

byte[] fileData = new byte[(int)this.getSize()]; 

 

当影片size长度大于2G则会强转失败,故作了如下修改:

package org.apache.commons.fileupload.disk;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemHeaders;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.ParameterParser;
import org.apache.commons.fileupload.util.Streams;
import org.apache.commons.io.IOUtils;
import org.apache.commons.io.output.DeferredFileOutputStream;

import java.io.*;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created by lucky god on 2017/4/24.
 */
public class DiskFileItem implements FileItem {
    private static final long serialVersionUID = 2237570099615271025L;
    public static final String DEFAULT_CHARSET = "ISO-8859-1";
    private static final String UID = UUID.randomUUID().toString().replace('-', '_');
    private static final AtomicInteger COUNTER = new AtomicInteger(0);
    private String fieldName;
    private final String contentType;
    private boolean isFormField;
    private final String fileName;
    private long size = -1L;
    private final int sizeThreshold;
    private final File repository;
    private byte[] cachedContent;
    private transient DeferredFileOutputStream dfos;
    private transient File tempFile;
    private File dfosFile;
    private FileItemHeaders headers;

    public DiskFileItem(String fieldName, String contentType, boolean isFormField, String fileName, int sizeThreshold, File repository) {
        this.fieldName = fieldName;
        this.contentType = contentType;
        this.isFormField = isFormField;
        this.fileName = fileName;
        this.sizeThreshold = sizeThreshold;
        this.repository = repository;
    }

    public InputStream getInputStream() throws IOException {
        if(!this.isInMemory()) {
            return new FileInputStream(this.dfos.getFile());
        } else {
            if(this.cachedContent == null) {
                this.cachedContent = this.dfos.getData();
            }

            return new ByteArrayInputStream(this.cachedContent);
        }
    }

    public String getContentType() {
        return this.contentType;
    }

    public String getCharSet() {
        ParameterParser parser = new ParameterParser();
        parser.setLowerCaseNames(true);
        Map params = parser.parse(this.getContentType(), ';');
        return (String)params.get("charset");
    }

    public String getName() {
        return Streams.checkFileName(this.fileName);
    }

    public boolean isInMemory() {
        return this.cachedContent != null?true:this.dfos.isInMemory();
    }

    public long getSize() {
        return this.size >= 0L?this.size:(this.cachedContent != null?(long)this.cachedContent.length:(this.dfos.isInMemory()?(long)this.dfos.getData().length:this.dfos.getFile().length()));
    }

    public byte[] get() {
        if(this.isInMemory()) {
            if(this.cachedContent == null) {
                this.cachedContent = this.dfos.getData();
            }

            return this.cachedContent;
        } else {
            if (this.getSize() > Integer.MAX_VALUE){
                return null;
            }

            byte[] fileData = new byte[(int)this.getSize()];
            BufferedInputStream fis = null;

            try {
                fis = new BufferedInputStream(new FileInputStream(this.dfos.getFile()));
                fis.read(fileData);
            } catch (IOException var12) {
                fileData = null;
            } finally {
                if(fis != null) {
                    try {
                        fis.close();
                    } catch (IOException var11) {
                        ;
                    }
                }

            }

            return fileData;
        }
    }

    public String getString(String charset) throws UnsupportedEncodingException {
        return new String(this.get(), charset);
    }

    public String getString() {
        byte[] rawdata = this.get();
        String charset = this.getCharSet();
        if(charset == null) {
            charset = "ISO-8859-1";
        }

        try {
            return new String(rawdata, charset);
        } catch (UnsupportedEncodingException var4) {
            return new String(rawdata);
        }
    }

    public void write(File file) throws Exception {
        if(this.isInMemory()) {
            FileOutputStream outputFile = null;
            BufferedInputStream fis = null;
            try {
                outputFile = new FileOutputStream(file);
//                outputFile.write(this.get());

                if (this.getSize() > Integer.MAX_VALUE){
                    byte[] temp = new byte[100*1024*1024];   //100M
                    int len;
                    fis = new BufferedInputStream(new FileInputStream(this.dfos.getFile()));
                    while ((len = fis.read(temp)) != -1){
                        outputFile.write(temp,0, len);
                        outputFile.flush();
                    }
                } else{
                    outputFile.write(this.get());
                }

            } finally {
                if(outputFile != null) {
                    outputFile.close();
                }
                if(fis != null) {
                    fis.close();
                }

            }
        } else {
            File outputFile1 = this.getStoreLocation();
            if(outputFile1 == null) {
                throw new FileUploadException("Cannot write uploaded file to disk!");
            }

            this.size = outputFile1.length();
            if(!outputFile1.renameTo(file)) {
                BufferedInputStream in = null;
                BufferedOutputStream out = null;

                try {
                    in = new BufferedInputStream(new FileInputStream(outputFile1));
                    out = new BufferedOutputStream(new FileOutputStream(file));
                    IOUtils.copy(in, out);
                } finally {
                    if(in != null) {
                        try {
                            in.close();
                        } catch (IOException var19) {
                            ;
                        }
                    }

                    if(out != null) {
                        try {
                            out.close();
                        } catch (IOException var18) {
                            ;
                        }
                    }

                }
            }
        }

    }

    public void delete() {
        this.cachedContent = null;
        File outputFile = this.getStoreLocation();
        if(outputFile != null && outputFile.exists()) {
            outputFile.delete();
        }

    }

    public String getFieldName() {
        return this.fieldName;
    }

    public void setFieldName(String fieldName) {
        this.fieldName = fieldName;
    }

    public boolean isFormField() {
        return this.isFormField;
    }

    public void setFormField(boolean state) {
        this.isFormField = state;
    }

    public OutputStream getOutputStream() throws IOException {
        if(this.dfos == null) {
            File outputFile = this.getTempFile();
            this.dfos = new DeferredFileOutputStream(this.sizeThreshold, outputFile);
        }

        return this.dfos;
    }

    public File getStoreLocation() {
        return this.dfos == null?null:this.dfos.getFile();
    }

    protected void finalize() {
        File outputFile = this.dfos.getFile();
        if(outputFile != null && outputFile.exists()) {
            outputFile.delete();
        }

    }

    protected File getTempFile() {
        if(this.tempFile == null) {
            File tempDir = this.repository;
            if(tempDir == null) {
                tempDir = new File(System.getProperty("java.io.tmpdir"));
            }

            String tempFileName = String.format("upload_%s_%s.tmp", new Object[]{UID, getUniqueId()});
            this.tempFile = new File(tempDir, tempFileName);
        }

        return this.tempFile;
    }

    private static String getUniqueId() {
        int limit = 100000000;
        int current = COUNTER.getAndIncrement();
        String id = Integer.toString(current);
        if(current < 100000000) {
            id = ("00000000" + id).substring(id.length());
        }

        return id;
    }

    public String toString() {
        return String.format("name=%s, StoreLocation=%s, size=%s bytes, isFormField=%s, FieldName=%s", new Object[]{this.getName(), this.getStoreLocation(), Long.valueOf(this.getSize()), Boolean.valueOf(this.isFormField()), this.getFieldName()});
    }

    private void writeObject(ObjectOutputStream out) throws IOException {
        if(this.dfos.isInMemory()) {
            this.cachedContent = this.get();
        } else {
            this.cachedContent = null;
            this.dfosFile = this.dfos.getFile();
        }

        out.defaultWriteObject();
    }

    private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
        in.defaultReadObject();
        if(this.repository != null) {
            if(!this.repository.isDirectory()) {
                throw new IOException(String.format("The repository [%s] is not a directory", new Object[]{this.repository.getAbsolutePath()}));
            }

            if(this.repository.getPath().contains("\u0000")) {
                throw new IOException(String.format("The repository [%s] contains a null character", new Object[]{this.repository.getPath()}));
            }
        }

        OutputStream output = this.getOutputStream();
        if(this.cachedContent != null) {
            output.write(this.cachedContent);
        } else {
            FileInputStream input = new FileInputStream(this.dfosFile);
            IOUtils.copy(input, output);
            this.dfosFile.delete();
            this.dfosFile = null;
        }

        output.close();
        this.cachedContent = null;
    }

    public FileItemHeaders getHeaders() {
        return this.headers;
    }

    public void setHeaders(FileItemHeaders pHeaders) {
        this.headers = pHeaders;
    }
}

 

对应包位置应与原位置一致,博文中包目录不变。

 

附文件下载

 

分享到:
评论

相关推荐

    netty-all-4.1.29.Final.jar最新版导入直接用

    它活跃和成长于用户社区,像大型公司 Facebook 和 Instagram 以及流行 开源项目如 Infinispan, HornetQ, Vert.x, Apache Cassandra 和 Elasticsearch 等,都利用其强大的对于网络抽象的核心代码。 Netty is a NIO ...

    Spring Boot整合FTPClient线程池的实现示例

    FTPClient 是一个基于 Java 的 FTP 客户端库,提供了丰富的 FTP 操作 API,例如上传、下载、删除文件等。然而,在高并发场景下,频繁创建和销毁 FTPClient 对象可能会对服务器造成很大的压力。 为了解决这个问题,...

    kafka处理超大消息的配置 org.apache.kafka.common.errors.RecordTooLargeException

    java.lang.RuntimeException: java.util.concurrent.ExecutionException: org.apache.kafka.common.errors.RecordTooLargeException: The request included a message larger than the max message size the server ...

    单点登录源码

    | ├── zheng-upms-common -- upms系统公共模块 | ├── zheng-upms-dao -- 代码生成模块,无需开发 | ├── zheng-upms-client -- 集成upms依赖包,提供单点认证、授权、统一会话管理 | ├── zheng-upms-rpc-...

    IDEA打包jar-解决找不到或无法加载主类 main的问题

    当Java运行时系统尝试执行jar文件时,它需要找到一个名为`main`的方法,该方法定义在主类中,通常以`public static void main(String[] args)`的形式存在。如果Java运行时找不到这个方法或者类的位置,就会抛出“找...

    eclipse 报错java.lang.ClassNotFoundException: com.mysql.jdbc.Driver错误解决

    一:查看你下载的MySQL和mysql-connector-java,如果不对应的话肯定会报错。 对应规则: mysql-connector-java-5 Connector/J version Driver Type JDBC version MySQL Server version Status 5.1 4 3.0, 4.0...

Global site tag (gtag.js) - Google Analytics