I have created a web application using ASP.NET MVC
Here I have added User to upload Image type or PDF file to upload to the system in one module.
So the user uploaded files I'm saving as bytes in the database table. Also, I'm saving the file type in another column in the table because when retrieving the file I'm checking if the file is image or pdf.
Thing is Image files are saved and retrieved without any error.
But Some PDF files when the user selected is uploaded without any error, But sometimes again retrieving the file in the details view, some pdf files are not opening. Most of the time used for this Google Chrome browser and, When I checked again it with Firefox, it opens normally.
So I asked users to use Firefox when accessing the system. But even further the error is still showed up. Then I'm checking the file in the database table, I got that some files are not saved in the table, but the file type is showing as octet-stream
.
I want to know why these pdf files are showing as octet-stream
and why it's not saving the attachment and is there any way to avoid this error?
This is my Converting attachment into byte code
public byte[] ConvertToBytes(HttpPostedFileBase image) {
byte[] imageBytes = null;
using(BinaryReader br = new BinaryReader(image.InputStream)) {
imageBytes = br.ReadBytes(image.ContentLength);
}
return imageBytes;
}
When Saving it It goes as
foreach(PurchasingItems item in appRequest.PurchasingItemsList) {
HttpPostedFileBase file = Request.Files["ImageData" + item.TempID];
item.Attachment = ConvertToBytes(file);
item.FileType = Path.GetFileName(file.ContentType);
}
This is how I retrieve the file to show.
public ActionResult RetrieveImage(int id) {
var q = from temp in db.GeneralItms where temp.Id == id select temp.Attachment;
var type = from t in db.GeneralItms 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;
}
}