Java 中客户端共享的下载文件已损坏

Downloaded file is corrupted shared by client in Java

我尝试使用从客户端获取的输入流在服务器端创建文件。

创建的文件大小与原始文件相同。但是当试图打开它时显示文件已损坏。

fileSharing.jsp 正在尝试共享文件 (发件人)

的客户端服务器
HttpURLConnection httpURLConnection = null;
OutputStream os = null;
InputStream is = null;
try {
    File fileObj = new File("D://test.pdf");
    out.print("File Length " + fileObj.length() + " Name " + fileObj.getName());
    URL url = new URL("http://localhost:2080/Receiver/fileupload?filename=test.pdf&filelength=" + fileObj.length());
    httpURLConnection = (HttpURLConnection) url.openConnection();
    httpURLConnection.setDoOutput(true);
    httpURLConnection.setRequestMethod("POST");
    httpURLConnection.setRequestProperty("Content-Type", "multipart/mixed");
    httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
    httpURLConnection.setRequestProperty("Cache-Control", "no-cache");
    httpURLConnection.setRequestProperty("Content-Disposition", "form-data; name=\"Dummy File Description\"");
    httpURLConnection.setChunkedStreamingMode(8192);
    httpURLConnection.connect();

    is = new BufferedInputStream(new FileInputStream(fileObj));
    os = new BufferedOutputStream(httpURLConnection.getOutputStream());

    byte[] buff = new byte[8192];
    int len = 0;
    while ((len = is.read(buff, 0, buff.length)) > 0) {
        os.write(buff, 0, len);
        os.flush();
    }
} catch (Exception e) {
    e.printStackTrace();
} finally {
    is.close();
    os.close();
    httpURLConnection.disconnect();
}

服务器端的 FileUploadController servlet 正在尝试下载文件 (接收方)

InputStream is = null;
OutputStream os = null;
try {
    is = request.getInputStream();
    int total = 0;
    int bytes = 0;
    os = new BufferedOutputStream(new FileOutputStream(new File("D://files//dummy.pdf")));
    byte[] buff = new byte[8192];
    while (true) {
        if ((bytes = is.read(new byte[8192])) == -1) {
            System.out.println("File shared successfully");
            System.out.println("Total " + total);
            break;
        }
        total = total + bytes;
        System.out.println("Length " + bytes);
        os.write(buff, 0, bytes);
        //os.flush();
    }
} catch (Exception e) {
    e.printStackTrace();
} finally {
    is.close();
    os.close();
}

FileUploadController的读取循环中你实例化了一个新的数组并读入其中,但是你没有坚持下去继续使用它:

 byte[] buff = new byte[8192];
 while(true){
     if((bytes = is.read(new byte[8192])) == -1){

但是,您 buff 写入文件(它将充满 0 字节,因此您将拥有一个长度正确的文件,但是它充满了 0 而不是实际数据)。

将最后一行替换为

     if((bytes = is.read(buff)) == -1){