The following is a snippet for uploading files using PHP. I am an Android developer and I want to upload a file. Which means I have to send a POST request to a URL that contains this script.
What is the parameter name that I should use if I want to upload a file?
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"];
}
When I try cURL, the file is uploaded successfully but when I do it via Java, it fails.
cURL
curl -F file=@call_me_now_2.wav http://some.site/upload/
Java Code
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();
}
});
Answered by this . But nevertheless an explanation.
One cannot read a binary file as done (as text). That gives problems with line endings, nul characters, character encodings, and again making it binary.
One normally would get the InputStream, here content
, and stream it out, without first reading all into memory.
import org.apache.commons.fileupload.util.Streams;
OutputStream out = response.getOutputStream();
Streams.copy(content, out, false);
Of course on posting a form with file upload, follow the mentioned answer.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.