1

My android application successfully sends files to a remote php server. Until know the server responds by sending back a simple string:

PHP Code

// if a file was posted
if($_FILES && $_POST){

    if(move_uploaded_file($file, $dir)) {
         echo "File successfully sent to server.";
    }

I can get this text answer with this peace of code:

Java Code

HttpResponse response = httpClient.execute(httpPost);
HttpEntity resEntity = response.getEntity();

// get server response
if (resEntity != null)  {    
    return EntityUtils.toString(resEntity).trim();
}

Now I don't want to get a simple text response, but i expect a whole file. I don't have much experience and got stuck:

PHP Code

if(move_uploaded_file($app, $upload_file . $file_ending)) {
    readfile($res_file); // read file and write it output buffer
}

Java Code

HttpResponse response = httpClient.execute(httpPost);
HttpEntity resEntity = response.getEntity();

if (resEntity != null)  
    return String.valueOf(resEntity.getContentLength()); 

getContentLength returns 14, which is definitely not the file size in byte.

How do I get a file as response from a PHP server?

null
  • 1,369
  • 2
  • 18
  • 38

1 Answers1

1

Are you sure that the file you are sending is not 14 bytes? Check that the reponse you are getting is not an error statment. If you are receiving a legitimate response, then response.getEntity().getContentLength() should display "the number of bytes of the content".

As for the PHP part, here is something others have used successfully:

if (file_exists($file)) {
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename='.basename($file));
    header('Content-Transfer-Encoding: binary');
    header('Expires: 0');
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    header('Pragma: public');
    header('Content-Length: ' . filesize($file));
    ob_clean();
    flush();
    readfile($file);
    exit;
}

See reference.

erad
  • 1,766
  • 2
  • 17
  • 26
  • This works. Thanks a lot. Could you please explain, why I have to add all these header lines? Why can't i just execute readfile($file)? – null Oct 09 '14 at 14:49
  • Honestly, I don't think you need it. Just something that might help with debugging. What I would advise is that you check that the file exists before you send it. – erad Oct 09 '14 at 14:53
  • 1
    Without these lines, i get the same error. Thus they are necessary. – null Oct 09 '14 at 14:54
  • Oh pardon me. I think it may have to do with the "Content-Type". By default it will send an object of type `application/x-www-form-urlencoded` – erad Oct 09 '14 at 14:55