我尝试将视频文件 (.mp4) 发送到服务器。我知道发送字节数组是一种非常过时的方法,但问题是我不能更改服务器,不允许这样做。
发送小于 1 mb 的文件时,一切都很好,但对于较大的文件,它就不起作用了。有谁知道如何解决这个问题??有可能吗?
服务器代码:($data中为实际字节数组,前面的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);
}
}