I am trying to implement a server using Java. When I try to send a file, such as video or pdf, the connection is always reset. I am currently using OpenJDK 11 and Ubuntu.
void binaryResponse(OutputStream clientOutput, File file) throws IOException {
int size= (int) file.length();
String responseStr="HTTP/1.1 200 OK\r\n";
responseStr+="Content-Type: application/force-download\r\n";
responseStr+="Content-Length: " + size + "\r\n\r\n";
clientOutput.write(responseStr.getBytes());
FileInputStream fis = new FileInputStream(file);
int bytes;
byte[] buffer = new byte[4*1024];
while (size > 0 && (bytes = fis.read(buffer, 0, Math.min(buffer.length, size))) != -1){
clientOutput.write(buffer, 0, bytes);
size -= bytes;
}
clientOutput.flush();
fis.close();
}
application/force-download
is not a valid media type (see Utility of HTTP header "Content-Type: application/force-download" for mobile? ).
You could use application/octet-stream
instead, but a better option is to send the correct media type for the file type, ie application/pdf
for a PDF file, etc (see How to get a file's Media Type (MIME type)? ), and then send a separate Content-Disposition: attachment
header to trigger a download.
Also, when creating the Content-Length
header, it is more efficient to use String.valueOf()
or String.format()
to convert the size
integer to a String
, rather than letting the operator+
do the conversion implicitly (see Concatenate integers to a String in Java for why).
Try this:
void binaryResponse(OutputStream clientOutput, File file) throws IOException {
int size = (int) file.length();
String responseStr = "HTTP/1.1 200 OK\r\n";
responseStr += "Content-Type: application/octet-stream\r\n";
responseStr += "Content-Length: " + String.valueOf(size) + "\r\n";
responseStr += "Content-Disposition: attachment; filename=\"" + file.getName() + "\"\r\n\r\n";
clientOutput.write(responseStr.getBytes());
FileInputStream fis = new FileInputStream(file);
int bytes;
byte[] buffer = new byte[4*1024];
while (size > 0 && (bytes = fis.read(buffer, 0, Math.min(buffer.length, size))) != -1){
clientOutput.write(buffer, 0, bytes);
size -= bytes;
}
clientOutput.flush();
fis.close();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.