以下は、PHP を使用してファイルをアップロードするためのスニペットです。私は 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 -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();
}
});