Why Is My Downloaded File Is Always Damaged or Corrupted

Why is my downloaded file is always damaged or corrupted?

That seems allot of code just to force-download, here is a nice function I use all the time. It will handle files over 2GB too.

<?php 
$file_id = (isset($_GET['id']) && (int)$_GET['id'] != 0) ? (int)$_GET['id'] : exit;

/*finding file info*/
$file = comon::get_all_by_condition('files', 'id', $file_id);
$path = $file['location'] . '/' . $file['file_name'];

if (!is_file($path)) {
echo 'File not found.('.$path.')';
} elseif (is_dir($path)) {
echo 'Cannot download folder.';
} else {
send_download($path);
}

return;

//The function with example headers
function send_download($file) {
$basename = basename($file);
$length = sprintf("%u", filesize($file));

header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . $basename . '"');
header('Content-Transfer-Encoding: binary');
header('Connection: Keep-Alive');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . $length);

set_time_limit(0);
readfile($file);
}
?>

my files (pdf, xlsx, docx ..) are downloaded corrupt or with errors, in Reactjs

This answer is by @hexebioc

fetchFile(){
axios({
url: `/someurl/thefiles/${this.props.file.id}`,
method: "GET",
headers: headers,
responseType: "blob" // important
}).then(response => {
const url = window.URL.createObjectURL(new Blob([response.data]));
const link = document.createElement("a");
link.href = url;
link.setAttribute(
"download",
`${this.props.file.name}.${this.props.file.mime}`
);
document.body.appendChild(link);
link.click();
});

}

render(){

return(

<button onClick={this.fetchFile}> Download file </button>

)

}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

Downloaded files are corrupted when buffer length is 1

len = stream.read(buffer);
read += len;
writableLocalFile.write(buffer, 0, len);

You must not use buffer.length as the bytes read, you need to use the return value of the read call. Because it might return a short read and then your buffer contains junk (0 bytes or data from previous reads) after the read bytes.

And besides calculating the remaining and using dynamic buffers just go for 16k or something like that. The last read will be short, which is fine.

Download file corrupt. Content-type not working?

I used this code to download pdfs:

header ("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header('Content-Type: application/octetstream');
header("Content-Transfer-Encoding: Binary");
header("Content-length: ".filesize($file));
header("Content-disposition: attachment; filename=\"".basename($filename)."\"");
readfile("$file");
}

This should be fine, and make sure there are no spaces or return characters (don't escape php at all is the best solution).

If you find your still having problems, open the corrupted file with notepad (there may be a php error warning inside).

Hope this helps!

Corrupt XLSX file after downloading

I had this same issue with AngularJS 1.6.1. When I called my HTTP GET service from the browser or from window.open("url"), the xlsx file was downloaded perfectly: 304628 bytes. However, the response.data provided by AngularJS instead had 289414 bytes and the Blob wrapper had 550963 bytes, which is what is downloaded as a corrupted file. This same behavior occurred if I return the xlsx in a zip.

I solved this by setting the XMLHttpRequest.responseType property as such:

$http.get(url, {responseType:'arraybuffer'});

File corrupted when I try to download via requests.get()

The problem was in an incorrect URL.
It loaded HTML instead of PDF.
Looking throw the site I found the URL that you were looking for.
Try this code and then open the document with pdf reader program.

import requests
import pathlib

def load_pdf_from(url:str, filename:pathlib.Path) -> None:
response:requests.Response = requests.get(url, stream=True)
if response.status_code == 200:
with open(filename, 'wb') as pdf_file:
for chunk in response.iter_content(chunk_size=1024):
pdf_file.write(chunk)
else:
print(f"Failed to load pdf: {url}")

url:str = 'https://www.schroders.com/hkrprewrite/retail/en/attachment2.aspx?fileid=e47b0366c44e4f33b04c20b8b6878aa7.pdf'

target_filename:pathlib.Path = pathlib.Path.cwd().joinpath('loaded_pdf.pdf')

load_pdf_from(url, target_filename)

ASP.Net MVC Razor Document Downloading as Corrupt

Coming back to answer this question. It turns out that I had forgotten to add the filesize to the download information, so when it was downloading it didn't know how large the file was supposed to be. We just had to add the following line of code:

Response.AddHeader("Content-Length", file.Length.ToString());

So to close everything together, this is what the download function looked like at the end:

    public void DownloadCompanyDoc(int id)
{
try
{
var getFile = rep.GetCompanyDocById(id);
var path = Path.Combine(HostingEnvironment.MapPath("~/Documents/CompanyDocs"), getFile);
FileInfo file = new FileInfo(path);

if (file.Exists)
{
Response.Clear();

Response.AppendHeader("content-disposition", "attachment; filename=" + getFile);
Response.AddHeader("Content-Length", file.Length.ToString());
Response.ContentType = System.Net.Mime.MediaTypeNames.Application.Octet;
Response.WriteFile(path);
Response.TransmitFile(path);
Response.Flush();
Response.End();
}
}
catch (Exception ex)
{
throw ex;
}
}

Hope this helps someone else in the future (pending someone else ever experiences this).



Related Topics



Leave a reply



Submit