我试图允许用户将15 MB文件上传到我的网络,从那里该文件应该发布到我的网络服务,接收响应(pdf文件)并将其提供给用户这样他就可以下载了。
但是,我以这样的网址结尾,没有提示下载任何内容,只有404错误:http://localhost:10080/Download?file=%PDF-1.4%%EF%BF%BD%EF%B (etc)
有些观点:
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 Web代码
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 Web服务代码
@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写入a
io.BytesIO()
并使用output = self.buff.getvalue()
1.-我对window location
事情做错了什么?
2.-我是否对文件类型做错了什么?
我进入这两天,现在我需要帮助。
感谢。
答案 0 :(得分:1)
但是,我以这样的网址结尾,没有提示下载任何内容,只有404错误:http://localhost:10080/Download?file=%PDF-1.4%%EF%BF%BD%EF%B(等)
您在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
}
})