[英]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.