通过网络发送带有自定义属性的文件

时间:2011-02-17 19:26:31

标签: java networking file-upload file-transfer

我想创建一个客户端 - 服务器程序,允许客户端将文件连同文件的一些信息(发件人姓名,描述等)一起发送到服务器。

该文件可能非常大,因为它可能是文本,图片,音频或视频文件,因此我不希望在发送之前将整个文件读入字节数组,我宁愿以块为单位读取文件,通过网络发送文件,然后允许服务器将块附加到文件末尾。

但是我遇到了如何最好地发送文件以及有关文件本身的一些信息的问题。我希望至少能够发送发件人的姓名和描述,这两者都将由用户输入到客户端程序中,但这可能会在将来发生变化,因此应该是灵活的。

这样做的好方法是什么,这样我才能“传输”正在发送的文件,而不是整体读取它然后发送?

3 个答案:

答案 0 :(得分:2)

套接字本身是字节流,所以你不应该有问题。我建议你有一个看起来像这样的协议。

只要总长度小于64 KB,就可以发送任意属性。随后是可以是任何63位长度的文件,并且一次发送一个块。 (缓冲区为8 KB)

如果您愿意,可以使用Socket发送更多文件。

DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
Properties fileProperties = new Properties();
File file = new File(filename);

// send the properties
StringWriter writer = new StringWriter();
fileProperties.store(writer, "");
writer.close();
dos.writeUTF(writer.toString());

// send the length of the file
dos.writeLong(file.length());

// send the file.
byte[] bytes = new byte[8*1024];
FileInputStream fis = new FileInputStream(file);
int len;
while((len = fis.read(bytes))>0) {
    dos.write(bytes, 0, len);
}
fis.close();
dos.flush();

阅读

DataInputStream dis = new DataInputStream(socket.getInputStream());
String propertiesText = dis.readUTF();
Properties properties = new Properties();
properties.load(new StringReader(propertiesText));
long lengthRemaining = dis.readLong();
FileOutputStream fos = new FileOutputStream(outFilename);
int len;
while(lengthRemaining > 0 
   && (len = dis.read(bytes,0, (int) Math.min(bytes.length, lengthRemaining))) > 0) {
      fos.write(bytes, 0, len);
      lengthRemaining -= len;
}
fos.close();

答案 1 :(得分:0)

您可以围绕众所周知的协议建立程序作为FTP。 要发送元信息,您只需创建一个包含信息的唯一名称的特殊文件。然后使用FTP传输用户文件和元文件。

否则,再次使用FTP作为文件,您可以在手写程序的客户端 - 服务器流中传输元数据。

答案 2 :(得分:0)

我建议使用http协议。服务器可以使用servlet实现,Apache HttpClient可以用于客户端。 This article有一些很好的例子。您可以在同一请求中发送文件和参数。这也是非常少的代码!

相关问题