如何解决如何使用Java HTTP Server发送文件?
This代码流摄像头和Java http服务器。
此浏览器中的此代码流网络摄像头的URL为http:// localhost:8080
我要使用相同的方法发送文件以供下载。
在这种方法中,java http服务器流网络摄像头。我想使用相同的方法从PC发送文件。
打开http:// localhost:8080时,它将在浏览器中下载文件。
网络摄像头流示例代码:
public class HttpStreamServer implements Runnable {
private BufferedImage img = null;
private ServerSocket serverSocket;
private Socket socket;
private final String boundary = "stream";
private OutputStream outputStream;
public Mat imag;
public HttpStreamServer(Mat imagFr) {
this.imag = imagFr;
}
public void startStreamingServer() throws IOException {
serverSocket = new ServerSocket(8080);
socket = serverSocket.accept();
writeHeader(socket.getOutputStream(),boundary);
}
private void writeHeader(OutputStream stream,String boundary)
throws IOException {
stream.write(("HTTP/1.0 200 OK\r\n" +
"Connection: close\r\n" +
"Max-Age: 0\r\n" +
"Expires: 0\r\n" +
"Cache-Control: no-store,no-cache,must-revalidate,pre-
check=0,post-check=0,max-age=0\r\n" +
"Pragma: no-cache\r\n" +
"Content-Type: multipart/x-mixed-replace; " +
"boundary=" + boundary + "\r\n" +
"\r\n" +
"--" + boundary + "\r\n").getBytes());
}
public void pushImage(Mat frame) throws IOException {
if (frame == null)
return;
try {
outputStream = socket.getOutputStream();
BufferedImage img = Mat2bufferedImage(frame);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(img,"jpg",baos);
byte[] imageBytes = baos.toByteArray();
outputStream.write(("Content-type: image/jpeg\r\n" +
"Content-Length: " + imageBytes.length + "\r\n" +
"\r\n").getBytes());
outputStream.write(imageBytes);
outputStream.write(("\r\n--" + boundary + "\r\n").getBytes());
} catch (Exception ex) {
socket = serverSocket.accept();
writeHeader(socket.getOutputStream(),boundary);
}
}
public void run() {
try {
System.out.print("go to http://localhost:8080 with browser");
startStreamingServer();
while (true) {
pushImage(imag);
}
} catch (IOException e) {
return;
}
}
public void stopStreamingServer() throws IOException {
socket.close();
serverSocket.close();
}
public static BufferedImage Mat2bufferedImage(Mat image)
throws IOException {
MatOfByte bytemat = new MatOfByte();
Imgcodecs.imencode(".jpg",image,bytemat);
byte[] bytes = bytemat.toArray();
InputStream in = new ByteArrayInputStream(bytes);
BufferedImage img = null;
img = ImageIO.read(in);
return img;
}
}
我想使用this方法发送文件。
我该怎么做?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。