2016-10-19 3 views
0

Я создаю java-программу, которая может загрузить файл (главным образом mp4) хостеру openload.co, используя их api, которые вы можете найти here.через java загруженный файл mp4 не воспроизводится/поврежден

Моя программа способна загружать видео mp4, но оно не воспроизводится. Когда я загружаю ранее загруженное видео и проверяю его данные через свойства файла, видео и звуковая информация отсутствуют, поэтому кажется, что сервер не знает, что делать с файловыми байтами, хотя он распознает контент- тип, размер и имя файла.

Я проверил Google и этот форум, но пока не нашел ответа.

Вот код, который касается процедуры загрузки. Надеюсь, кто-то знает, чего не хватает.

private static String uploadFile(URL uploadURL, Path file, String fileName, String fileNameWithType) throws IOException{ 
    /*the size of the file, which is to be uploaded */ 
    long s = Files.size(file); 
    /*the amount of additional bytes sent with the file */ 
    long offset = 220; 
    /*the sum of the filesize and additional bytes */ 
    long actualBodySize = offset + s; 

    // returned server response 
    String response = null; 
    //HTTP line-break 
    String crlf = "\r\n"; 
    //mainly needed for end of multipart/form-data request 
    String twoHyphens = "--"; 
    //the fields are separated by this boundary, a random number 
    String boundary = "---------------------"+Long.toString(System.currentTimeMillis()); 

//--------------------------------------------------------------------------------------------------------  
    HttpsURLConnection OutputConnection = (HttpsURLConnection) uploadURL.openConnection(); 
    OutputConnection.setDoOutput(true); 
//--------------------------------------------------------------------------------------------------------   
    OutputConnection.setRequestProperty("Content-Type","multipart/form-data;boundary=" + boundary); 
    //allows java to start sending data via network immediatly 
    OutputConnection.setFixedLengthStreamingMode(actualBodySize); 
    OutputConnection.setRequestProperty("Connection", "Keep-Alive"); 
    OutputConnection.setRequestProperty("Cache-Control", "no-cache"); 
//--------------------------------------------------------------------------------------------------------                       
//setting up the I/O-Streams 

//OutputConnection.connect(); //not needed, getOutputStream does connect() on its own 
    try(InputStream fileInput = newInputStream(file, READ); 
     BufferedInputStream bfileInput = new BufferedInputStream(fileInput); 
     OutputStream fileOutput = OutputConnection.getOutputStream(); 
     BufferedOutputStream bfileOutput = new BufferedOutputStream(fileOutput); 
     DataOutputStream dfileOutput = new DataOutputStream(bfileOutput)){ 
//--------------------------------------------------------------------------------------------------------- 
//  manually writing the multipart/form-data request 
     dfileOutput.writeBytes(twoHyphens + boundary + crlf); 
     dfileOutput.writeBytes("Content-Disposition: form-data; name=\"" + 
     fileName + "\"; filename=\"" + 
     fileNameWithType + "\"" + crlf); 
     dfileOutput.writeBytes(crlf); 
     dfileOutput.writeBytes("Content-Type: video/mp4"+crlf); 
//  dfileOutput.writeBytes("Content-Transfer-Encoding: binary" + crlf + crlf); 
//--------------------------------------------------------------------------------------------------------------- 
//  uploading the file 
     for(int byteCode = bfileInput.read(); byteCode >= 0; byteCode = bfileInput.read()){ 
      dfileOutput.write(byteCode); 
     } 
//---------------------------------------------------------------------------------------------------------------    
//  manually writing the end-part of the multipart/form-data request 
     dfileOutput.writeBytes(crlf); 
     dfileOutput.writeBytes(twoHyphens + boundary + twoHyphens + crlf); 
     dfileOutput.flush(); 
//---------------------------------------------------------------------------------------------------------------- 
//  setting up inputstream in order to get the server response 
     ... 
//  extracting the download-url of the json-server-response 
     ... 

    } 
    OutputConnection.disconnect(); 
    return response; 
} 
+0

Вы утверждаете, что переносите контент в Base64, но это не так. – Kayaman

+0

Мой плохой, я забыл его удалить. Я тестировал разные вещи, найденные ive, но сервер, похоже, все равно игнорирует поле кодирования контента, так что это не проблема. – javaman

+0

Предоставьте ссылку на ** небольшое ** ранее загруженное тестовое видео. Идея состоит в том, чтобы проверить содержимое байта файла (пропал ли заголовок каких-либо дополнительных байтов, которые повреждены? ... и т. Д.). Сделайте тестовый файл за несколько секунд, если вам нужно ... Мы не можем объяснить, почему он не играет, если мы не можем увидеть/проверить, что с ним не так. –

ответ

0

Я выяснил, что случилось. Я сравнил фактический размер самого тестового видео и загруженного. Размер загружаемого файла был на 25 байт больше оригинала. Оказалось, что эта линия была добавлена ​​на videofilebytes, по какой-либо причине:

dfileOutput.writeBytes("Content-Type: video/mp4"+crlf); 

Теперь, когда я удалил это все работает отлично.

Смежные вопросы