这是上传文件的功能(我在asynctask中使用它)。 我从stackoverflow上的例子中获取了这段代码:
public JSONObject postFile(String fileName) throws Exception {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(SERVER);
MultipartEntityBuilder multipartEntity =
MultipartEntityBuilder.create();
multipartEntity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
multipartEntity.addPart("file", new FileBody(new File(fileName)));
post.setEntity(multipartEntity.build());
HttpResponse response = client.execute(post);
HttpEntity entity = response.getEntity();
is = entity.getContent();
// response.getStatusLine(); // CONSIDER Detect server complaints
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "UTF-8"));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
Log.e("JSON", json);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
entity.consumeContent();
client.getConnectionManager().shutdown();
return jObj;
}
处理邮件请求的php文件:
if ($_FILES){
$uploads_dir = 'uploads/';
$uploadname = $_FILES["file"]["name"];
if (move_uploaded_file($_FILES['file']['tmp_name'], $uploads_dir.$uploadname))
$response["success"] = 1;
else
$response["success"] = 0;
echo json_encode($response);
file_put_contents("log.txt",serialize($_FILES));
}
图片未上传。它给每次成功“0”。
这是log.txt文件:
a:1:{s:4:"file";a:5:{s:4:"name";s:12:"IMAG0284.jpg";s:4:"type";s:24:"application/octet-stream";s:8:"tmp_name";s:36:"/home/autost02/.system/tmp/phplsAIRP";s:5:"error";i:0;s:4:"size";i:623552;}}