【发布时间】:2012-04-19 09:16:37
【问题描述】:
以下是使用PHP上传文件的sn-p。我是一名 Android 开发人员,我想上传一个文件。这意味着我必须向包含此脚本的 URL 发送 POST 请求。
如果我想上传文件,我应该使用什么参数名称?
PHP
if (file_exists("upload/" . $_FILES["file"]["name"])) {
echo $_FILES["file"]["name"] . " already exists. ";
} else {
move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $_FILES["file"]["name"]);
echo "https://some.site/upload/" . $_FILES["file"]["name"];
}
当我尝试 cURL 时,文件上传成功,但当我通过 Java 上传时,它失败了。
cURL
curl -F file=@call_me_now_2.wav http://some.site/upload/
Java 代码
File f = new File("call_me_now_11.wav");
HttpPost filePost = new HttpPost("https://some.site/upload/");
FileEntity fileEntity = new FileEntity(f, "audio/wav");
filePost.setEntity(fileEntity);
HttpClient client = new DefaultHttpClient();
client.execute(filePost, new BasicResponseHandler() {
@Override
public String handleResponse(HttpResponse response)
throws HttpResponseException, IOException {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
int c = 0;
StringBuilder builder = new StringBuilder();
while((c = content.read()) != -1) {
builder.append((char) c);
}
System.out.println(builder.toString());
return builder.toString();
}
});
【问题讨论】: