Я создал pdf на serveride (golang), тогда я хочу загрузить этот pdf tough api call. Я использовал запрос ajax post. этот запрос направляется в следующий рабочий стол ExportReport
. но мой загруженный pdf-документ - пустая страница. Существует ошибка произойти из-за установки Content-Length в заголовке запроса Ошибка:Загрузка PDF не работает с serveride в golang
http: wrote more than the declared Content-Length
2016/12/20 14:37:39 http: multiple response.WriteHeader calls
Эта ошибка разбита PDF download.please пойти, хотя мои фрагменты кода.
func ExportReport(w http.ResponseWriter, r *http.Request) *core_commons.AppError {
url := "https://mydomainname/reporting/repository/dashboard.pdf"
timeout := time.Duration(5) * time.Second
cfg := &tls.Config{
InsecureSkipVerify: true,
}
transport := &http.Transport{
TLSClientConfig: cfg,
ResponseHeaderTimeout: timeout,
Dial: func(network, addr string) (net.Conn, error) {
return net.DialTimeout(network, addr, timeout)
},
DisableKeepAlives: true,
}
client := &http.Client{
Transport: transport,
}
resp, err := client.Get(url)
if err != nil {
fmt.Println(err)
}
defer resp.Body.Close()
w.Header().Set("Content-Disposition", "attachment; filename=dashboard.pdf")
w.Header().Set("Content-Type", r.Header.Get("Content-Type"))
w.Header().Set("Content-Length", r.Header.Get("Content-Length"))
_, err = io.Copy(w, resp.Body)
if err != nil {
fmt.Println(err)
}
return nil
}
Ниже приведены способы вызова запроса ajax.
$.ajax({
type: "POST",
url: '/reporting/api/report/export',
data: JSON.stringify(payload),
contentType: 'application/pdf',
success: function(response, status, xhr) {
// check for a filename
var filename = "";
var disposition = xhr.getResponseHeader('Content-Disposition');
if (disposition && disposition.indexOf('attachment') !== -1) {
var filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
var matches = filenameRegex.exec(disposition);
if (matches != null && matches[1]) filename = matches[1].replace(/['"]/g, '');
}
var type = xhr.getResponseHeader('Content-Type');
var blob = new Blob([response], { type: type });
if (typeof window.navigator.msSaveBlob !== 'undefined') {
// IE workaround for "HTML7007: One or more blob URLs were revoked by closing the blob for which they were created. These URLs will no longer resolve as the data backing the URL has been freed."
window.navigator.msSaveBlob(blob, filename);
} else {
var URL = window.URL || window.webkitURL;
var downloadUrl = URL.createObjectURL(blob);
if (filename) {
// use HTML5 a[download] attribute to specify filename
var a = document.createElement("a");
// safari doesn't support this yet
if (typeof a.download === 'undefined') {
window.location = downloadUrl;
} else {
a.href = downloadUrl;
a.download = filename;
document.body.appendChild(a);
a.click();
}
} else {
window.location = downloadUrl;
}
setTimeout(function() { URL.revokeObjectURL(downloadUrl); }, 100); // cleanup
}
}
});
Нет гарантии, что указанный вами URL установит 'Content-Length', и поэтому вы должны установить его в своем ответе, если он отличен от нуля. – icza