上传文件停止,并在套接字异常上读取意外的 EOF

新手上路,请多包涵

有时当我尝试在远程 vps 上上传文件时出现此异常(上传过程停止在 60%)

 06-Jan-2016 11:59:36.801 SEVERE [http-nio-54000-exec-9] org.apache.catalina.core.StandardWrapperValve.invoke Servlet.service() for servlet [mvc-dispatcher] in context with path [] threw exception [Request processing failed;
nested exception is org.springframework.web.multipart.MultipartException: Could not parse multipart servlet request;
nested exception is org.apache.commons.fileupload.FileUploadBase$IOFileUploadException: Processing of multipart/form-data request failed. Unexpected EOF read on the socket]
with root cause
 java.io.EOFException: Unexpected EOF read on the socket

Google Chrome 连接丢失,就像服务器关闭一样,我得到 ERR_CONNECTION_ABORTED

我在 spring mvc 中上传这样的文件

public void save_file(MultipartFile upfile , String path){

        try {

            File fichier = new File( path ) ;
            byte[] bytes = upfile.getBytes();
            BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream( fichier ));
            stream.write(bytes);
            stream.close();
            System.out.println( "You successfully uploaded " + upfile.getOriginalFilename() + "!" );

        } catch (Exception e) {
            System.out.println( "You failed to upload " + upfile.getOriginalFilename() + " => " + e.getMessage() ); ;
        }

}

我的控制器:

 @RequestMapping(value = "/administration/upload", method = RequestMethod.POST)
public String Upload_AO_journal(
        @ModelAttribute  UploadForm uploadForm,
                Model map , HttpServletRequest request, HttpSession session ) throws ParseException, UnsupportedEncodingException {

我的豆子

public class UploadForm {

    ...
    public MultipartFile scan;

那么如何解决这个问题呢?

原文由 Hayi 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 2.1k
2 个回答

你试过流吗?

代码:

<form method="POST" onsubmit="" ACTION="url?${_csrf.parameterName}=${_csrf.token}" ENCTYPE="multipart/form-data">

控制器:

  @RequestMapping(
        value = "url", method = RequestMethod.POST
)
public void uploadFile(
        @RequestParam("file") MultipartFile file
) throws IOException {

 InputStream input = upfile.getInputStream();
 Path path = Paths.get(path);//check path
 OutputStream output = Files.newOutputStream(path);
 IOUtils.copy(in, out); //org.apache.commons.io.IOUtils or you can create IOUtils.copy

}

所有对我有用的 spring 4.0 和 spring security。

其次,你应该检查http连接是否超时。 Chrome 不支持该配置。因此,您可以使用 firefox 并在此处关注 http://morgb.blogspot.com.es/2014/05/firefox-29-and-http-response-timeout.html

原文由 ahll 发布,翻译遵循 CC BY-SA 3.0 许可协议

出现此问题是因为您关闭流直到流写入整个数据。

错误的方法:

 stream.write(bytes);
stream.close();

正确的路:

 try (BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(fichier)))
{
    stream.write(data);
}

写入整个数据后,您应该关闭流。

原文由 eg04lt3r 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题