我正在编写一个允许将图像上传到服务器的 android 应用程序(使用 Cakephp)。我可以像这个解决方案一样使用纯 php: 将图像从 android 上传到 cakephp 服务器 我的问题是我不知道如何处理我的控制器将文件移动到 cakephp 的 img 目录。我已经尝试使用下面的代码,但它不起作用。我真的很感谢你的助手。
$target_path = "./";
$target_path = $target_path . basename( $_FILES['picture']['name']);
if(move_uploaded_file($_FILES['picture']['tmp_name'], $target_path)) {
echo "The file ". basename( $_FILES['picture']['name']).
" has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";
}
这是android上的代码
try {
// open a URL connection to the Server
FileInputStream fileInputStream = new FileInputStream(newFile);
URL url = new URL(url_upload);
// 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("profilepicture",
newFile.getAbsolutePath());
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes(("Content-Disposition: form-data; name=\"picture\";filename=\""
+ newFile.getAbsolutePath() + "\"" + 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 multiple part form data necessary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// Responses from the server (code and message)
serverResponseCode = conn.getResponseCode();
String serverResponseMessage = conn.getResponseMessage();
if (serverResponseCode == 200) {
Log.i("uploadFile", "HTTP Response is : "
+ serverResponseMessage + ": " + serverResponseCode);
}
// after download show image in gallery
context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,
Uri.parse("file://"
+ Environment.getExternalStorageDirectory())));
// close the streams //
fileInputStream.close();
dos.flush();
dos.close();
} catch (MalformedURLException ex) {
ex.printStackTrace();
Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
} catch (Exception e) {
e.printStackTrace();
Log.e("Upload file to server Exception",
"Exception : " + e.getMessage(), e);
}