通过网络发送文件时如何指定文件结尾 [英] How to specify end of file when sending it over network
问题描述
我的servlet使用FileInputStream.read()从二进制文件读取。如果到达文件末尾,则返回-1。然后,它通过响应流将文件的字节发送给客户端。
My servlet reads from a binary file using the FileInputStream.read(). This returns -1 if end of file is reached. It then sends the bytes of the file to the client over the response stream.
然后我想通过响应流发送文件的md5哈希的字节。我应该如何从文件的md5中拆分文件的末尾,以便客户端知道哪些字节是哪个?我无法发送-1字节,因为这样流就无法正常工作。
I want to then send the bytes of a md5 hash of the file over the response stream. How should i split the end of file from the md5 of the file so that the client knows which bytes are which? I can't send a -1 byte because then the stream stops working.
我是否可以发送其他任何字节来通知文件末尾,我知道不可能在实际文件中,因此也就不可能表明文件末尾
Are there any other bytes i can send to signal end of file that i know could not possibly be inside the actual file, and so not possibly signal the end of the file before it actually ends?
推荐答案
假设您可以依靠文件不进行更改,那么我将读取文件一次并计算MD5哈希,将其设置为标头,然后将文件写为完整正文。对于客户端来说,这比将主体分成两部分要容易得多。
Assuming you can rely on the file not to change, I would read the file once and compute the MD5 hash, set that as a header, and then write the file out as the complete body. That's likely to be easier for the client to handle than splitting the body into two parts.
如果文件足够小,则可以将其写入 ByteArrayOutputStream
在读取/哈希它时,避免不得不读取两次-但是,如果文件很大,则可能不想占用该内存。
If the file is small enough, you could write it into a ByteArrayOutputStream
as you read/hash it, to avoid having to read it twice - but if the file is large, you probably don't want to take that memory hit.
另一种选择是将散列存储在文件系统中-首先进行负责文件散列的写入。这样,您只需要对其哈希一次即可;您可以随时对它进行哈希处理,以在必要时对它们进行 verify 验证。
Another option is to store the hash in the file system - make whatever's writing the file in the first place responsible for hashing it. That way you only need to hash it once; you could always hash it as you read it to verify the hash if necessary.
这篇关于通过网络发送文件时如何指定文件结尾的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!