Chào cả nhà,
Mình đang làm một phần nhỏ cho ứng dụng của mình, hiện tại mình cần cho phép client download file từ server.
Trên server code bằng flask, mình có dùng
try:
current_dir = os.path.dirname(os.path.realpath(__file__))
file_path = os.path.join(current_dir, "backups.zip")
return send_file(file_dir, as_attachment=True)
except Exception as e:
return {"message": str(e)}, 500
Mình dùng trình duyệt hoặc swagger thì nó tải bình thường, giờ vấn đề mình gặp là chưa biết cách tải từ client mình code bằng reactJS có sử dụng thư viện axios. Mình tải về nó ra 1 file zip trống trơn không có nội dung. Sau khi research một hồi thì mình có thấy cách dùng như sau:
// Call API
export function exportDatabase(filename, password) {
return axios({
method: Methods.GET,
url: `/exporter/database`,
params: buildQuery({ filename, password }),
responseType: 'arraybuffer',
});
}
// Xử lý
exportDatabase(fileNameToExport, password)
.then((response) => {
const url = window.URL.createObjectURL(new Blob([response.data]));
const link = document.createElement('a');
link.href = url;
const filename = response.headers['content-disposition'].split(
'filename=',
)[1];
link.setAttribute('download', filename); // or any other extension
document.body.appendChild(link);
link.click();
setIsSubmitting(false);
cleanState();
})
.catch((err) => {
console.log('err.response :>> ', err.response);
updateActionWithDatabase({
errorMessage: err.response.data.toString(),
});
setIsSubmitting(false);
});
Dùng cách này mình download được file ngon lành, nhưng lại gặp vấn đề khác là khi tải file bị gặp lỗi, server sẽ thảy ra một message lỗi. Lúc này ở client, mình không đọc được nội dung lỗi do là nó đang là dạng arraybuffer
. Loay hoay cả ngày trời không được nên lên hỏi cả nhà tìm hướng xử lý.
Tiện mình cũng muốn hỏi làm sao để test download file như này bằng PostMan luôn, trước giờ mình chỉ làm với return text, json… đây là lần đầu mình làm việc với file và sẽ còn làm dài dài nên thiếu kiến thức ở đâu nhờ cả nhà chỉ luôn nhé.
Chân thành cảm ơn cả nhà nhiều