我使用PHP上傳從Android的一些圖像服務器。 圖片文件正在上傳,但是當我試圖查看該文件時,它顯示的是破碎的圖片,不知道究竟是什麼問題。 上傳在服務器上顯示的的AsyncTask 的Android代碼圖片上傳問題,從機器人到PHP服務器
FileInputStream fileInputStream;
HttpURLConnection connection;
URL url;
DataOutputStream outputStream;
int bytesRead,bytesAvailable,bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
File selectedFile = new File(selectedImagePath);
try
{
fileInputStream = new FileInputStream(selectedFile);
url = new URL("The url of my server");
connection= (HttpURLConnection)url.openConnection();
Log.v(TAG,"connection established");
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection","Keep-Alive");
connection.setRequestProperty("ENCTYPE","multipart/form-data");
connection.setRequestProperty("Content-Type","multipart/form-data;boundary=*****");
connection.setRequestProperty("uploaded_file",selectedImagePath);
outputStream = new DataOutputStream(connection.getOutputStream());
outputStream.writeBytes("--*****\r\n");
outputStream.writeBytes("Content-Disposition:form-data;name=\"uploaded_file\";filename=\""+selectedImagePath+"\""+"\r\n");
outputStream.writeBytes("\r\n");
outputStream.writeBytes("--*****\r\n");
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable,maxBufferSize);
buffer = new byte[bufferSize];
bytesRead = fileInputStream.read(buffer,0,bufferSize);
while (bytesRead>0)
{
outputStream.write(buffer,0,bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable,maxBufferSize);
bytesRead = fileInputStream.read(buffer,0,bufferSize);
}
outputStream.writeBytes("\r\n");
outputStream.writeBytes("--*****\r\n");
int serverResponseCode = connection.getResponseCode();
String serverResponseMessage = connection.getResponseMessage();
if(serverResponseCode == HttpURLConnection.HTTP_OK) {
String line;
StringBuilder sb = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
while ((line = reader.readLine()) != null) {
sb.append(line);
}
}
fileInputStream.close();
outputStream.flush();
outputStream.close();
PHP Code:
$file_path = basename($_FILES['uploaded_file']['name']);
if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $file_path))
{
echo "success";
} else
{
echo "fail";
}
'outputStream.write(緩衝液,0,緩衝區大小);'。這應該是'outputStream.write(buffer,0,bytesRead);'。 – greenapps
請比較原始文件和上傳文件的大小。 – greenapps
感謝您的回覆,但現在已完成!問題在於關閉文件塊。 – Akki