【问题标题】:Downloaded file is corrupted shared by client in Java下载的文件已损坏,由 Java 中的客户端共享
【发布时间】:2020-01-13 01:54:38
【问题描述】:

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

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

客户端服务器上的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正在尝试下载文件(Receiver)

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();
}

【问题讨论】:

  • 您正在读取一个缓冲区并从另一个缓冲区写入。不要在循环内部冲洗。

标签: java jakarta-ee file-io inputstream outputstream


【解决方案1】:

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){

【讨论】:

  • 代码运行良好。但是,如果我启用身份验证过滤器,它就会中断。你能帮帮我吗?
猜你喜欢
  • 1970-01-01
  • 2014-08-09
  • 2020-11-10
  • 2019-01-21
  • 1970-01-01
  • 2019-03-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多