我正在尝试通过php将图片从Android设备上传到服务器,但我遇到了一些问题。当文件上传时,文件似乎到达服务器(我可以看到几百kb的tmp文件),但文件没有像我想要的那样以.jpg文件的形式保存到目录中。我得到的服务器响应是500 - 内部错误。
我在服务器上放了一个基本的html表单,以便我可以从浏览器测试php上传文件,并且使用我的电脑和手机上的浏览器上传了一张图片。所以这只是我的应用程序无法正常工作。这是服务器/ 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.";
}
?>