MultipartFile 文件上传时 java.io.EOFException 连接断开的解决办法

        java.io.EOFException: Unexpected EOF read on the socket 
        at org.apache.coyote.http11.Http11InputBuffer.fill
    
我的问题是因为使用的异步请求,文件还未上传成功,我就跳转到了其他页面,致使连接断开,报了这个错误
    
    下面是错误的js代码, 将代码中的window.history.back(-1) 注释掉,代码就正常了
    
    


    upload(obj) {
                let reader = new FileReader()
                reader.readAsDataURL(obj.target.files[0]);
                reader.onload = function () {
                    app.imgs.push({img: obj.target.files[0], src: this.result})
                    app.shuoImgs.push({imgSrc: obj.target.files[0].name})
                    app.index++
                }
            },
            shuoAdd() {
                if (!(this.imgs.length === 0)) {
                    this.postImgs()
                }
                axios.post('/shuo/add',
                    {
                        content: this.shuo,
                        imgs: this.shuoImgs
                    }).then(response=> {
                    // window.history.back(-1)
                })
            },
            postImgs() {
                let formData = new FormData();
                let imgs = []
                console.log(this.imgs)
                for (let img of this.imgs) {
                    imgs.push(img.img)
                    formData.append("files", img.img)
                }
                axios.post('/shuo/upload', formData)
                    .then(response=>{
                        console.log(response.data);
                        console.log(this.shuo)
                        console.log(this.shuoImgs)
                    })
                    .catch(function (error) {
                        alert("上传失败");
                        console.log(error);
                    });
            }
            
 下面是后端代码
            
            
    @PostMapping("upload")
    @ResponseBody
    public String upload(MultipartFile [] files) {
        for (MultipartFile file : files) {
            System.out.println(file);
            if (Objects.isNull(file) || file.isEmpty()) {
                return "文件为空,请重新上传";
            }
            try {
                System.out.println(1);
                byte[] bytes = file.getBytes();
                Path path = Paths.get(UPLOAD_FOLDER + file.getOriginalFilename());
                System.out.println(UPLOAD_FOLDER);
                System.out.println(path.toUri());
                //如果没有files文件夹,则创建
                System.out.println(path);
                if (!Files.isWritable(path)) {
                    Files.createDirectories(Paths.get(UPLOAD_FOLDER));
                }
                //文件写入指定路径
                Files.write(path, bytes);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return "成功";
    }

猜你喜欢

转载自blog.csdn.net/qinkaiyuan94/article/details/80366979