繁体   English   中英

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM