In my asp.net MVC web application, there are some views that can upload PDF files and Image files.
When retrieving the same data from the database user can view the attachments.
But some PDF files I noticed, the User selected and uploaded the files are saved in the DB.
When receiving the file, it says file corrupted or cannot open. So I checked the file type from the database and it was saved as octet-stream and the attachment was not saved in the table.
Can anyone tell me why this happens and how to avoid this from happening?
These are the codes I'm currently using.
jQuery for file validation
function checkImage(obj) {
var fileExtension = ['jpeg', 'jpg', 'png', 'gif', 'bmp', 'pdf'];
var ResponceImgId = $(obj).data('id');
const fileSize = obj.files[0].size / 1024 / 1024; // in MiB
const fileSizeRule = 3.0;
if ($.inArray($(obj).val().split('.').pop().toLowerCase(), fileExtension) == -1) {
alert('error', 'Upload Error', 'Only .jpeg, .jpg, .png, .gif, .bmp ,pdf formats are allowed.');
} else if (fileSize > fileSizeRule) {
alert("File size should be less than 3 MB. Please add a attachment less than 3 MB");
} else {
var files = obj.files;
var reader = new FileReader();
name = obj.value;
reader.onload = function (e) {
$('#' + ResponceImgId).prop('src', e.target.result);
};
reader.readAsDataURL(files[0]);
}
}
</script>
Converting the file to byte
//region converting attachments to byte
public byte[] ConvertToBytes(HttpPostedFileBase Attachment) {
byte[] imageBytes = null;
BinaryReader reader = new BinaryReader(Attachment.InputStream);
imageBytes = reader.ReadBytes((int) Attachment.ContentLength);
return imageBytes;
}
This is how to retrieve the file.
public ActionResult RetrieveImage(int id) {
var q = from temp in db.PurchasingItems where temp.Id == id select temp.Attachment;
var type = from t in db.PurchasingItems where t.Id == id select t.FileType;
string fileType = type.First().ToString();
byte[] cover = q.First();
if (cover != null) {
if (fileType == "pdf") {
return File(cover, "pdf");
} else {
return File(cover, "image/jpg");
}
} else {
return null;
}
}