0
我嘗試發送視頻文件(.mp4)到服務器。我知道發送字節數組是一個非常過時的方法,但問題是我不能更改服務器,不允許。發送大字節數組到php服務器
當發送小於1 MB的文件時,一切正常,但大文件不起作用。有誰知道如何解決?它有可能嗎?
服務器代碼(在$數據是實際的字節數組,前面的128個字符都只是用於文件管理,比如文件名和ID)
<?php
//get data
if (!isset($HTTP_RAW_POST_DATA))
$HTTP_RAW_POST_DATA = file_get_contents("php://input");
//cass -------------------------------------------------------------
$filename = substr($HTTP_RAW_POST_DATA, 0, 128);
$filename = trim($filename, " ");
$filename = explode(";",$filename);
$fname = $filename[0];
$q_id = $filename[1];
$data = substr($HTTP_RAW_POST_DATA, 128);
$length = strlen($data);
$file = fopen("cassDebug.txt","w");
$textout = "QID: $q_id NAME: $fname LENGTH: $length";
fwrite($file,$textout);
fclose($file);
// write file
if(strlen($data)>0){
$FSize = strlen($data);
$f = fopen("media/$fname",'w');
fwrite($f,$data,$FSize);
fclose($f);
}
?>
Java代碼:
try
{
FileInputStream fileInputStream = new FileInputStream(new File(pathToOurFile));
URL url = new URL(urlServer);
connection = (HttpURLConnection) url.openConnection();
// Allow Inputs & Outputs
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/octet-stream");
connection.connect();
OutputStream os = connection.getOutputStream();
String fileName = makeLength(fname, fname.length());
String comma = ";";
String audioQuestionId = makeLength(QID, 128 - fname.length() - comma.length());
os.write(fileName.getBytes());
os.write(comma.getBytes());
os.write(audioQuestionId.getBytes());
// Initialize byte array for data transfer
byte[] dataBuffer = new byte[2*1024];
// Get total bytes in the file
long totalBytes = fileInputStream.available();
System.out.println("Total bytes: "+totalBytes);
long bytesRead = 0;
int n = 0;
while ((n = fileInputStream.read(dataBuffer, 0, 2*1024)) != -1) {
os.write(dataBuffer, 0, n);
bytesRead += n;
}
System.out.println(connection.getResponseCode());
System.out.println(connection.getResponseMessage());
fileInputStream.close();
os.flush();
os.close();
connection.disconnect();
}
catch (Exception ex){
System.out.println(ex);
}
}