In my MVC project,
I have a file upload page. In this page, I want to preview files. When a file inserted into my file input element, I send this file to my controller(named: "FilesController") and i try to get this file if it is pdf or not. If this file is not pdf so i convert it to pdf and resend to view with AJAX. the whole process is run with ajax. There is no page refreshing.
The problem is, sometimes when i upload CSV file, This file goes to server and server tries to convert it to PDF byte array and finally sends to View. In view, I try to convert this byte array as base64 and convert to buffer array. and Finally I create blob. I insert this blob to FilePreview iframe element and try to show file.
Like I said, CSV does not work. But It works with PDF PNG. I understand this problem, sometimes server converts pdfs badly. So my willing is simple. If it is a malformed PDF, I won't show it to iframe.
How can I do this?
Here is my ajax code:
`
function ConvertFilesToBytes(files) {
//if (files.length > 0) {
var formData = new FormData();
formData.append("file", files);
$.ajax({
method: "POST",
url: "/FileManagement/PreviewFileFromBytes",
processData: false,
contentType: false,
data: formData,
beforeSend: function () {
$("#FilePreviewFrame").text("Ön izleme getiriliyor... Lütfen Bekleyiniz ...");
},
success: function (res) {
var bufferedBytes = _base64ToArrayBuffer(res.fileBytes);
var blob = new Blob([bufferedBytes], { type: res.fileContentType });
var url = URL.createObjectURL(blob);
$("#FilePreviewFrame").attr('src', url);
$("#FilePreviewFrame").addClass('border border-info ');
//SetFilesToFrame(res);
},
error: function (xhr) {
log("Ön izleme oluşturulamadı!", "red");
}
});
}
`
Here is my buffer array converter:
`
function _base64ToArrayBuffer(base64) {
var binary_string = window.atob(base64);
var len = binary_string.length;
var bytes = new Uint8Array(len);
for (var i = 0; i < len; i++) {
bytes[i] = binary_string.charCodeAt(i);
}
return bytes.buffer;
}
`
Note: I do not need show all types of files. I need to show wellformed files. But when it comes malformed file, I want to prevent showing into iframe.
So
- Can we prevent IFRAME to not download file?
- Can we detect malformed PDF?
If 1 or 2, This question will be successed :) ...
I did not found any response from google or stackoverflow.
I look at here: how to prevent download when the pdf load to iframe? iframe - prevent it from downloading anything