Android デバイスから PHP 経由でサーバーに画像をアップロードしようとしていますが、いくつか問題があります。ファイルがアップロードされると、ファイルがサーバーに到達しているように見えます (数百 kb の tmp ファイルを確認できます) が、ファイルが .jpg ファイルとしてディレクトリに保存されていません。サーバーの応答は 500 - 内部エラーです。
サーバーに基本的な html フォームを配置して、ブラウザーから php アップロード ファイルをテストできるようにしました。PC と電話のブラウザーを使用して、問題なく画像をアップロードしました。だから、それは私のアプリが動作していないだけです。サーバー/phpの構成に問題がありますか、それともアップロード方法に問題がありますか? コードは次のとおりです。
HttpURLConnection connection = null;
DataOutputStream outputStream = null;
String pathToOurFile = listOfFiles.getFirst().toString();
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1*1024*1024;
try {
FileInputStream fileInputStream = new FileInputStream(new File(pathToOurFile) );
URL url = new URL(serverAddress);
connection = (HttpURLConnection) url.openConnection();
// Allow Inputs & Outputs
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
// Enable POST method
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);
outputStream = new DataOutputStream( connection.getOutputStream() );
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
outputStream.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + pathToOurFile +"\"" + lineEnd);
outputStream.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// Read file
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(lineEnd);
outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// Responses from the server (code and message)
int serverResponseCode = connection.getResponseCode();
Log.v("UPLOAD*********", "Server Code: " + serverResponseCode);
if (serverResponseCode == 200) {
successfulUploads++;
listOfFiles.removeFirst();
} else {
numberOfTries++;
}
fileInputStream.close();
outputStream.flush();
outputStream.close();
} catch (Exception ex) {
numberOfTries++;
}
そして、ここにphpファイルがあります:
<?php
$target = "uploads/";
$target = $target . basename( $_FILES['uploaded']['name']) ;
if(move_uploaded_file($_FILES['uploaded']['tmp_name'], $target))
{
echo "The file ". basename( $_FILES['uploaded']['name']). " has been uploaded";
}
else {
echo "Sorry, there was a problem uploading your file.";
}
?>