允许用户在上传文件后下载生成的 pdf 文件
Allow user to download a generated pdf file after uploading a file
我试图让用户上传一个 15 MB 的文件到我的网站,然后该文件应该 posted 到我的网络服务,接收响应(pdf 文件)并将其提供给用户,以便他可以下载。
但是,我以这样的 URL 结束,没有提示下载任何东西,只有 404 错误:http://localhost:10080/Download?file=%PDF-1.4%%EF%BF%BD%EF%B (etc)
几点:
- 首先我会压缩文件
- 由于上一点,我使用 Ajax 到 post 文件
Ajax代码
$("#file").on("change", function(evt) {
var files = evt.target.files;
/* Create zip file representation */
var zip = new JSZip();
/* Name, content */
zip.file("data.zip", files[0]);
zip.generateAsync({
compression: 'DEFLATE',
type: 'blob'
}).then(function(zc) { // Function called when the generation is complete
/* Create file object to upload */
var fileObj = new File([zc], "compressed-data");
/* form data oject */
var formData = new FormData();
/* $('#file')[0].files[0] */
formData.append('attachments', fileObj);
$.ajax({
type: "POST",
url: $("form#data").attr("action"),
data: formData,
contentType: false,
processData: false,
success: function (returnValue, textStatus, jqXHR ) {
window.location = '/Download?file=' + returnValue;
}
})
Python 网页代码
def post(self):
attachments = self.request.POST.getall('attachments')
#handle the attachment
_attachments = [{'content': f.file.read(),
'filename': f.filename} for f in attachments]
# Use the App Engine Requests adapter. This makes sure that Requests uses
# URLFetch.
requests_toolbelt.adapters.appengine.monkeypatch()
#web service url
url = 'http://localhost:8080'
files = {'attachments': _attachments[0]["content"]}
resp = requests.post(url, files=files)
self.response.headers[b'Content-Type'] = b'application/pdf; charset=utf-8'
self.response.headers[b'Content-Disposition'] = b'attachment; filename=report.pdf'
self.response.out.write(resp.content)
Python 网络服务代码
@app.route('/', methods=['POST'])
def hello():
#the attached ZIPPED raw data
f = request.files["attachments"]
#to unzip it
input_zip = ZipFile(f)
#unzip
data = [input_zip.read(name) for name in input_zip.namelist()]
generator = pdfGenerator(io.BytesIO(data[0]))
return generator.analyzeDocument()
pdf生成器使用Reportlab,将pdf写在
io.BytesIO()
和 returns 它与 output = self.buff.getvalue()
1.- 我对 window location
做错了什么?
2.- 我是不是文件类型有问题?
我已经花了两天时间,现在我需要帮助。
谢谢。
However, I'm ending in a URL like this with no prompt to download anything, just a 404 error: http://localhost:10080/Download?file=%PDF-1.4%%EF%BF%BD%EF%B (etc)
这就是您在 window.location = '/Download?file=' + returnValue;
中的要求,您将用户重定向到 /Download
。
当您致电服务时,您应该要求 Blob
回复。然后,使用saveAs
(or FileSaver.js, a polyfill)触发下载。
据我所知,$.ajax
不允许您下载开箱即用的二进制内容(它会尝试从 UTF-8 解码您的二进制文件并破坏它)。使用 jQuery 插件(如 jquery.binarytransport.js)或直接使用 xhr。
$.ajax({
type: "POST",
url: $("form#data").attr("action"),
data: formData,
contentType: false,
processData: false,
dataType: 'binary', // using jquery.binarytransport.js
success: function (returnValue, textStatus, jqXHR ) {
// Default response type is blob
saveAs(returnValue, "result.pdf"); // using FileSaver.js
}
})
我试图让用户上传一个 15 MB 的文件到我的网站,然后该文件应该 posted 到我的网络服务,接收响应(pdf 文件)并将其提供给用户,以便他可以下载。
但是,我以这样的 URL 结束,没有提示下载任何东西,只有 404 错误:http://localhost:10080/Download?file=%PDF-1.4%%EF%BF%BD%EF%B (etc)
几点:
- 首先我会压缩文件
- 由于上一点,我使用 Ajax 到 post 文件
Ajax代码
$("#file").on("change", function(evt) {
var files = evt.target.files;
/* Create zip file representation */
var zip = new JSZip();
/* Name, content */
zip.file("data.zip", files[0]);
zip.generateAsync({
compression: 'DEFLATE',
type: 'blob'
}).then(function(zc) { // Function called when the generation is complete
/* Create file object to upload */
var fileObj = new File([zc], "compressed-data");
/* form data oject */
var formData = new FormData();
/* $('#file')[0].files[0] */
formData.append('attachments', fileObj);
$.ajax({
type: "POST",
url: $("form#data").attr("action"),
data: formData,
contentType: false,
processData: false,
success: function (returnValue, textStatus, jqXHR ) {
window.location = '/Download?file=' + returnValue;
}
})
Python 网页代码
def post(self):
attachments = self.request.POST.getall('attachments')
#handle the attachment
_attachments = [{'content': f.file.read(),
'filename': f.filename} for f in attachments]
# Use the App Engine Requests adapter. This makes sure that Requests uses
# URLFetch.
requests_toolbelt.adapters.appengine.monkeypatch()
#web service url
url = 'http://localhost:8080'
files = {'attachments': _attachments[0]["content"]}
resp = requests.post(url, files=files)
self.response.headers[b'Content-Type'] = b'application/pdf; charset=utf-8'
self.response.headers[b'Content-Disposition'] = b'attachment; filename=report.pdf'
self.response.out.write(resp.content)
Python 网络服务代码
@app.route('/', methods=['POST'])
def hello():
#the attached ZIPPED raw data
f = request.files["attachments"]
#to unzip it
input_zip = ZipFile(f)
#unzip
data = [input_zip.read(name) for name in input_zip.namelist()]
generator = pdfGenerator(io.BytesIO(data[0]))
return generator.analyzeDocument()
pdf生成器使用Reportlab,将pdf写在
io.BytesIO()
和 returns 它与 output = self.buff.getvalue()
1.- 我对 window location
做错了什么?
2.- 我是不是文件类型有问题?
我已经花了两天时间,现在我需要帮助。
谢谢。
However, I'm ending in a URL like this with no prompt to download anything, just a 404 error: http://localhost:10080/Download?file=%PDF-1.4%%EF%BF%BD%EF%B (etc)
这就是您在 window.location = '/Download?file=' + returnValue;
中的要求,您将用户重定向到 /Download
。
当您致电服务时,您应该要求 Blob
回复。然后,使用saveAs
(or FileSaver.js, a polyfill)触发下载。
据我所知,$.ajax
不允许您下载开箱即用的二进制内容(它会尝试从 UTF-8 解码您的二进制文件并破坏它)。使用 jQuery 插件(如 jquery.binarytransport.js)或直接使用 xhr。
$.ajax({
type: "POST",
url: $("form#data").attr("action"),
data: formData,
contentType: false,
processData: false,
dataType: 'binary', // using jquery.binarytransport.js
success: function (returnValue, textStatus, jqXHR ) {
// Default response type is blob
saveAs(returnValue, "result.pdf"); // using FileSaver.js
}
})