我正在尝试使用我在网上发现的几个来源将图像上传到我的服务器。我一直试图用几种方法做到这一点,但是它们似乎都不起作用。从本质上讲,我有一个我想从我的设备上传到服务器的图像。连接成功,服务器上的PHP文件似乎正在响应。这是我的代码进行上传。请注意,这是在AsyncTask中包装的:
ANDROID:
FileInputStream fileInputStream = new FileInputStream(imgFile);
URL url = new URL("xxx/UPLOAD_IMG.php");
// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true); // Allow Inputs
conn.setDoOutput(true); // Allow Outputs
conn.setUseCaches(false); // Don't use a Cached Copy
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("ENCTYPE", "multipart/form-data");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
conn.setRequestProperty("uploaded_file", fileName);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""
+ fileName + "\"" + lineEnd);
dos.writeBytes(lineEnd);
// create a buffer of maximum size
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// read file and write it into form...
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
// send multipart form data necesssary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// Responses from the server (code and message)
int serverResponseCode = conn.getResponseCode();
String serverResponseMessage = conn.getResponseMessage();
Log.i("uploadFile", "HTTP Response is : "
+ serverResponseMessage + ": " + serverResponseCode);
Log.i("A", "");
if (serverResponseCode == 200) {
// SUCCESS
}
//close the streams //
fileInputStream.close();
dos.flush();
dos.close();
和服务器上的PHP:
<?php
$file_path = "/images";
$file_path = $file_path . basename( $_FILES['uploaded_file']['name']);
if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $file_path)) {
echo 'Success';
} else {
echo 'fail';
}
?>
我已将服务器上的文件夹权限设置为:777以尝试解决问题。但这并没有解决任何问题。我还尝试将Image直接存储在数据库中作为BLOB,但这导致数据的加载时间更长。可能是PHP路径不正确吗?我是否必须以不同方式设置路径?
我在这里做错了什么?这有什么替代方案?答案对很多人都有好处,因为我发现很多人都遇到过类似的问题。
编辑:我已将整个代码更改为新内容。但它仍然不起作用。