所以我有一個學校的作業,其中客戶端必須發送無限制的文件到服務器。我這樣做了我的想法。發送無限的文件從客戶端到服務器
- 客戶端將無限制的文件發送到服務器。
- 服務器將通過客戶端上傳的文件重定向到我的WAMP的服務器文件夾
我已經工作的代碼,但是這個代碼只能從客戶端發送1個文件服務器。我還希望上傳文件的文件名增加,因爲在我的代碼中它只使用1個文件名,所以如果更多客戶端上傳文件,它們將覆蓋舊文件名。
例如:file01.rar接下來上傳file02.rar等等。
這裏是我的服務器代碼:
public void run() {
filePath = "C:/wamp/www/file.rar";
byte[] aByte = new byte[1];
int bytesRead;
InputStream is = null;
try {
is = clientSocket.getInputStream();
} catch (IOException ie) {
ie.printStackTrace();
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
if (is != null) {
FileOutputStream fos = null;
BufferedOutputStream bos = null;
try {
fos = new FileOutputStream(filePath);
bos = new BufferedOutputStream(fos);
bytesRead = is.read(aByte, 0, aByte.length);
do {
baos.write(aByte);
bytesRead = is.read(aByte);
} while (bytesRead != -1);
bos.write(baos.toByteArray());
bos.flush();
bos.close();
} catch (IOException ie) {
ie.printStackTrace();
}
}
}
這裏是我的客戶端代碼:
BufferedOutputStream bos = null;
try {
bos = new BufferedOutputStream(s.getOutputStream());
} catch (IOException ie) {
ie.printStackTrace();
}
if (bos != null) {
File uploadFile = new File(clientFacultyUploadTextField.getText());
byte[] myFileSize = new byte[(int)uploadFile.length()];
FileInputStream fis = null;
try {
fis = new FileInputStream(uploadFile);
} catch (FileNotFoundException fife) {
fife.printStackTrace();
}
BufferedInputStream bis = new BufferedInputStream(fis);
try {
bis.read(myFileSize, 0, myFileSize.length);
bos.write(myFileSize, 0, myFileSize.length);
bos.flush();
bos.close();
clientFacultyUploadTextField.setText("Upload complete...");
} catch (IOException ie) {
ie.printStackTrace();
}
}
關於SO的第一個問題和這麼好的格式化,+1 :) – Abubakkar