Скачать файл с URL как вложение

0

Я не могу установить правильные заголовки для загрузки файла из URL. Ниже код просто показывает содержимое URL-адреса в браузере вместо загрузки.

$file_name = "image1.jpg";
$content_type = "image/jpeg";
$url = "http://ctan.imsc.res.in/macros/latex/contrib/incgraph/example.jpg";

header('Pragma: public');   // required
header('Expires: 0');       // no cache
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Last-Modified: '.gmdate ('D, d M Y H:i:s', filemtime ($file_name)).' GMT');
header('Cache-Control: private',false);
header("Content-type: ".$content_type);
header("Cache-Control: no-store, no-cache");
header("Content-disposition: attachment; filename=".$file_name);
header("Location: ".$url);
exit(0);

Заранее спасибо.

Теги:
attachment

4 ответа

0

Загрузите файл с url (в списке) и сохраните файл с фамилией url, используя python

import urllib.request as urllib2
import re,os
for url in open('C:\\Users\\SRINU\\Desktop\\Election_pdfs_urls\\33.txt'):
  possible_urls = re.findall(r'(https?://[^\s]+)', url)
  for links in possible_urls:
    response = urllib2.urlopen(links.format(url.encode('utf-8')))
    filename_w_ext = os.path.basename(links)
    file = open(filename_w_ext, 'wb')
    file.write(response.read())
    file.close()
0

этот код прекрасно работает для загрузки с URL:

set_time_limit(0);

//File to save the contents to
$fp = fopen ('file.type', 'w+');

$url = "http://yoursite.come/file.type";

//Here is the file we are downloading, replace spaces with %20
$ch = curl_init(str_replace(" ","%20",$url));

curl_setopt($ch, CURLOPT_TIMEOUT, 50);

//give curl the file pointer so that it can write to it
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

$data = curl_exec($ch);//get curl response

//done
curl_close($ch);
?>
  • 0
    Приведенный выше код загрузит файл на мой сервер, и мне не нужно загружать файл на сервер. Я должен передать этот файл пользователю непосредственно для загрузки на его / ее ПК / ноутбуки.
0
$originalPath = $_REQUEST['path'];  //path with filename
$fileName = $_REQUEST['fileName'];  // filename for downloaded file name    
if (file_exists($originalPath)) {
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename='.basename($fileName));
    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($originalPath));
    ob_clean();
    flush();
    readfile($originalPath);
    exit;
} else {
    echo 'FILE_NOT_FOUND';
}
  • 0
    У меня есть только URL, а не абсолютный путь к файлу. Я должен использовать URL, а не фактическое местоположение файла. URL является внешним источником не с моего сервера, у меня нет фактического пути к этому файлу.
0

используя этот код, вы можете сохранить изображение на нашем сервере, и вы можете загрузить изображение, используя мой верхний код.

file_put_contents("Tmpfile.jpg", fopen("http://ctan.imsc.res.in/macros/latex/contrib/incgraph/example.jpg", 'r'));

Ещё вопросы

Сообщество Overcoder
Наверх
Меню