使用spring将大文件上传到tomcat时出现问题

时间:2015-11-04 17:47:48

标签: java spring spring-mvc tomcat

我有一个应用程序将视频文件上传到我的服务器,但最后一次尝试加载4GB视频文件并上传文件只有368Mb,总共4GB。

这是控制器的代码。

@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
public @ResponseBody List<String> handleFileUpload(@RequestParam("idClient") String idClient,
        @RequestParam("idChannel") String idChannel, @RequestParam("idPlayList") String idPlayList,
        MultipartHttpServletRequest request, HttpServletResponse response) {

    StringBuffer sb = new StringBuffer();
    List<String> response = new ArrayList<String>();
    Iterator<String> itr = request.getFileNames();
    MultipartFile file = null;

    while (itr.hasNext()) {

        file = request.getFile(itr.next());

        if (!file.isEmpty()) {

            sb.setLength(0);

            sb.append(tmpFolder).append(idClient).append("_").append(idChannel).append("_").append(idPlayList)
                    .append("_").append(file.getOriginalFilename());

            try {

                byte[] bytes = file.getBytes();

                BufferedOutputStream stream = new BufferedOutputStream(
                        new FileOutputStream(new File(sb.toString())));

                stream.write(bytes);

                stream.close();

                response.add("File " + file.getOriginalFilename() + " uploading.");

            } catch (IOException e) {

                response.add("File " + file.getOriginalFilename() + " not upload.");

            }

        } else {

            response.add("File no subido " + file.getOriginalFilename() + " file is empty ! .");

        }

    }

    return response;
}

那会发生什么?

感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

我已经解决了!谢谢 问题是当你加载超过2GB的文件超过一个字节数组的最大大小可以支持是因为这个文件没有完全解决这个问题创建一个缓冲区,将文件读入块或块。

public void copyPartsBufferFile(InputStream input, Integer bufferSize, String fullPathDetiny) {

BufferedOutputStream stream = null;

    try {

        stream = new BufferedOutputStream(new FileOutputStream(new File(fullPathDetiny)));

        ReadableByteChannel rbc = Channels.newChannel(input);
        ByteBuffer buffer = ByteBuffer.allocate(bufferSize);
        byte[] bytes;

        while (rbc.read(buffer) >= 0) {
            buffer.flip();
            bytes = buffer.array();
            stream.write(bytes);
            buffer.clear();
        }

    } catch (FileNotFoundException e) {

    } catch (IOException e) {

    } catch (Exception e) {

    } finally {

    }

}

我留下我的代码以防有人发生同样的事情!

问候。