Java 通过URLConnection将音频文件从客户端传输到Http服务器

Java 通过URLConnection将音频文件从客户端传输到Http服务器,java,file-transfer,Java,File Transfer,我目前正在学校做一个编程项目。我需要成功地将音频文件(MIDI格式)从客户端发送到Http服务器。我自己也尝试过这样做,并且在互联网和Stackoverflow论坛上做了很多研究。目前,可以将文件从客户端发送到服务器,但在服务器端,音频文件不可播放 以下是客户端代码: private static void sendPOST() throws IOException{ final int mid = 1; final String POST_URL = "http://local

我目前正在学校做一个编程项目。我需要成功地将音频文件(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();
以下是服务器端代码:

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所以我已经深入调查了这件事。我发现了几个问题:

  • 您混合了二进制和基于字符的I/O。当您在客户端处理它时,服务器很难处理这个问题
  • 您忘记指定要发送到服务器的文件的大小。在服务器端,您无法知道(传入文件的)大小(除非有人事先告诉您)
我编辑了您的代码,并得出了以下结论:

客户: 服务器:
@覆盖
公共无效句柄(HttpExchange t)引发IOException{
字符串CRLF=“\r\n”;
int fileSize=0;
字符串文件_TO_RECEIVED=“C://root//m”+musikerid+“hp”+(hörprobenzaehler+1)+“.mid”;
文件f=新文件(接收到的文件);
如果(!f.exists()){
f、 createNewFile();
}
InputStream输入=t.getRequestBody();
字符串nextLine=“”;
做{
nextLine=readLine(输入,CRLF);
if(nextLine.startsWith(“内容长度:”){
文件大小=
整数.parseInt(
nextLine.replaceAll(“,”).substring(
“内容长度:”.Length()
)
);
}
System.out.println(nextLine);
}而(!nextLine.equals(“”);
byte[]midFileByteArray=新字节[fileSize];
int readOffset=0;
while(readOffset0){
int nextByte=is.read();
如果(下一字节<-1){
抛出新IOException(
“读取当前行时到达流的末尾!”);
}
lineBytes[i]=(字节)下一个字节;
if(lineBytes[i++]==分隔符[off++]){
if(off==分隔符长度){
返回新字符串(
lineBytes,0,i-separator.length,“UTF-8”);
}
}
否则{
关=0;
}
if(i==lineBytes.length){
抛出新IOException(“超出最大行长度:“+i”);
}
}
抛出新IOException(
“读取当前行时到达流的末尾!”);
}

所以我对这件事做了更深入的研究。我发现了几个问题:

  • 您混合了二进制和基于字符的I/O。当您在客户端处理它时,服务器很难处理这个问题
  • 您忘记指定要发送到服务器的文件的大小。在服务器端,您无法知道(传入文件的)大小(除非有人事先告诉您)
我编辑了您的代码,并得出了以下结论:

客户: 服务器:
@覆盖
公共无效句柄(HttpExchange t)引发IOException{
字符串CRLF=“\r\n”;
int fileSize=0;
字符串文件_TO_RECEIVED=“C://root//m”+musikerid+“hp”+(hörprobenzaehler+1)+“.mid”;
文件f=新文件(接收到的文件);
如果(!f.exists()){
f、 createNewFile();
}
InputStream输入=t.getRequestBody();
字符串nextLine=“”;
做{
nextLine=readLine(输入,CRLF);
if(nextLine.startsWith(“内容长度:”){
文件大小=
整数.parseInt(
nextLine.replaceAll(“,”).substring(
“内容长度:”.Length()
)
);
}
System.out.println(nextLine);
}而(!nextLine.equals(“”);
byte[]midFileByteArray=新字节[fileSize];
int readOffset=0;
while(readOffset0){
int nextByte=is.read();
如果(下一字节<-1){
抛出新IOException(
“读取当前行时到达流的末尾!”);