【发布时间】:2020-10-23 09:32:40
【问题描述】:
我目前正在我的学校从事一个编程项目。我需要将音频文件(MIDI 格式)从客户端成功发送到 Http 服务器。我自己已经尝试过这样做,并在互联网和 Stackoverflow 论坛上进行了大量研究。目前可以将文件从客户端发送到服务器,但在服务器端,音频文件无法播放。
以下是客户端代码:
private static void sendPOST() throws IOException{
final int mid = 1;
final String POST_URL = "http://localhost:8080/musiker/hörprobe?mid="+mid;
final File uploadFile = new File("C://Users//Felix Ulbrich//Desktop//EIS Prototype MIDIs//Pop//BabyOneMoreTime.mid");
String boundary = Long.toHexString(System.currentTimeMillis());
String CRLF = "\r\n";
String charset = "UTF-8";
URLConnection connection = new URL(POST_URL).openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
try (
OutputStream output = connection.getOutputStream();
PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, charset), true);
){
writer.append("--" + boundary).append(CRLF);
writer.append("Content-Disposition: form-data; name=\"binaryFile\"; filename=\"" + uploadFile.getName() + "\"").append(CRLF);
writer.append("Content-Type: " + URLConnection.guessContentTypeFromName(uploadFile.getName())).append(CRLF);
writer.append("Content-Transfer-Encoding: binary").append(CRLF);
writer.append(CRLF).flush();
Files.copy(uploadFile.toPath(), output);
output.flush();
writer.append(CRLF).flush();
writer.append("--" + boundary + "--").append(CRLF).flush();
int responseCode = ((HttpURLConnection) connection).getResponseCode();
System.out.println(responseCode);
}
}
以下是服务器端代码:
int FILE_SIZE = Integer.MAX_VALUE-2;
int bytesRead = 0;
int current = 0;
FileOutputStream fos = null;
BufferedOutputStream bos = null;
byte[] mybytearray = new byte[FILE_SIZE];
String FILE_TO_RECEIVED = "C://root//m"+musikerid+"hp"+(hörprobenzaehler+1)+".mid";
File f = new File(FILE_TO_RECEIVED);
if(!f.exists()){
f.createNewFile();
}
InputStream input = t.getRequestBody();
fos = new FileOutputStream(FILE_TO_RECEIVED);
bos = new BufferedOutputStream(fos);
bytesRead = input.read(mybytearray,0,mybytearray.length);
current = bytesRead;
do{
bytesRead = input.read(mybytearray, current, mybytearray.length-current);
if(bytesRead >= 0){
current += bytesRead;
}
}while(bytesRead>-1);
bos.write(mybytearray,0,current);
bos.flush();
fos.close();
bos.close();
t.sendResponseHeaders(200, 0);
input.close();
我现在很绝望,因为我找不到任何解决这个问题的方法。我需要使用 HTTP 服务器,但不需要使用 TCP 协议(现在通过流使用)。我想了一个通过 ftp 的解决方案,所以我不需要先将文件转换为字节数组。我认为问题就在那里。服务器无法从字节数组正确创建音频文件(midi 文件)。如果你们中的任何人知道解决方案。请问,我需要你的帮助:D
你好,Gizpo
【问题讨论】:
-
bos.write(mybytearray,0,current);看起来很可疑!您确定要将整个 HTTP 请求写入您的.mid文件吗? -
哦,好的,非常感谢。所以我需要从输入流中提取midi文件(字节数组)本身并将其写入文件。打算在这里寻找解决方案。
-
再次浏览我的代码后,我看到我实际上只通过客户端的流发送文件: Files.copy(uploadFile.toPath(), output);还是我错了?
-
您正在发送整个交易。当您将字符串附加到您的
PrintWriter对象时,您实际上是在写入您的套接字的OutputStream。您需要在服务器上做的是逐行读取您的InputStream,直到您读取一个空字符串行。然后通过read(...)阅读你的midi。 -
还有一件事。对于读取字符流,我建议将BufferedReader 和BufferedInputStream 用于二进制流。两者都可以从
InputStream构造。
标签: java file-transfer