我是一名 Android 编程的新手。我一直在尝试使用以下代码从我的应用程序将多个图像上传到服务器。这里,image[] 数组与其他数据(如用户名、密码等)一起作为 namevaluepair 发送到服务器。
Java 代码:
public void post(String url, List<NameValuePair> nameValuePairs) {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
try {
MultipartEntity entity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
for (int index = 0; index < nameValuePairs.size(); index++) {
if (nameValuePairs.get(index).getName()
.equalsIgnoreCase("image[]")) {
// If the key equals to "image[]", we use FileBody to transfer
// the data
Log.d("key", "image");
Log.d("image path", nameValuePairs.get(index).getName());
entity.addPart(nameValuePairs.get(index).getName(),
new FileBody(new File(nameValuePairs.get(index)
.getValue())));
} else {
// Normal string data
Log.d("tag", nameValuePairs.get(index).getName());
// Log.d("tag", nameValuePairs.get(index).getValue());
entity.addPart(
nameValuePairs.get(index).getName(),
new StringBody(nameValuePairs.get(index).getValue()));
}
}
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost);
HttpEntity enttiy = response.getEntity();
Log.d("server response to post data", EntityUtils.toString(enttiy));
} catch (IOException e) {
e.printStackTrace();
}
}
PHP代码(工作版本):
<?php
$target_path = "user_uploaded_photos/";
for($i=0;$i<count($_FILES["image"]["name"]);$i++){
$fileData = pathinfo(basename($_FILES["image"]["name"][$i]));
$username = $_POST['username'];
print_r($fileData);
$date = date('Y_m_d_H_i_s');
$newfilename = $username.$i.$date.".".$fileData['extension'];
if (move_uploaded_file($_FILES["image"]["tmp_name"][$i], $target_path."/".$newfilename))
{
echo "The image {$_FILES['image']['name'][$i]} was successfully uploaded and added to the gallery<br />";
}
else
{
echo "There was an error uploading the file {$_FILES['image']['name'][$i]}, please try again!<br />";
}
} $location = $_POST['location'];
//other fields and database operations ommitted
我需要翻译的内容是关于IT技术的,涉及cakephp网站的使用问题。在cakephp中,我使用以下名称值对:
nameValuePair
.add(new BasicNameValuePair("UserDatum[user_id]", "2"));
发送这样的字符串值对我有效。但是当我声明images[]数组时,图片已上传但无法从$_FILES访问。我已经按照以下方式声明了images[]数组:
for (String s : imagePath) {
nameValuePair.add(new BasicNameValuePair("UserDatum[images][]",
s));
Log.d("image-path", s);
}
在这里,imagePath是包含图像路径的字符串数组列表。在应用程序中声明"UserDatum[images][]"是否是正确的方式?它可以在发布的php中工作,但在cake php中只有字符串值被发布,而没有图像。我尝试了其他库,比如ion。但是,我只能上传一个照片,而不能使用数组结构。请评论或指向正确的方向,以便在单个帖子中发布多个图像和字符串。
echo $_FILES['image']['name'][$i]
可能不安全。 - klenium