Opening a byte stream file using asp.net mvc - file

Im my asp.net mvc application I have a enclosing the thumb image of the file in an aspx page loaded in an iframe. I want to open the file with an Open/Save dialogbox. The file is uploaded to the database in image datatype.
My aspx page has the following html in it:
<li class="thumpimage">
<%=Html.Hidden("attachmtId", item.ILDAttachmentId) %>
<img src="<%=imgurl %>" alt="test" height="81" width="76" />
<span class="thumb_descrp">
<%=item.ILDAttachmentName %></span></li>
The jquery part is as follows
$(document).ready(function() {
$(".thumpimage").click(function() {
var attchmtId = $("#attachmtId").val();
alert(attchmtId);
$.post('/Instruction/OpenInstnDoc', { attchId: attchmtId });
});
});
And the function in the controller is
public ActionResult OpenInstnDoc(int attchId)
{
Attachment objAttach = new Attachment();
objAttach = objAttach.GetAttachmentById(attchId);
byte[] theData = objAttach.BinaryFile;
Response.AddHeader("content-length", theData.Length.ToString());
Response.AddHeader("content-disposition", "inline; filename=" + objAttach.AttachmentName + "");
return File(theData, objAttach.MineType);
}
I am not able open the file. Can anyone help me on this?

You cannot use ajax to stream file content to the browser and expect to be prompted with a file open/save dialog. Instead of the call to $.post, try
$(document).ready(function() {
$(".thumpimage").click(function() {
var attchmtId = $("#attachmtId").val();
alert(attchmtId);
//$.post('/Instruction/OpenInstnDoc', { attchId: attchmtId });
window.location.href = "/Instruction/OpenInstnDoc/" + attchmtId;
});
});

Related

How to display mysql image in angularjs? (AngularJs -> Node.js -> abc.com -> mysql)

I am hosting a website on Heroku with Node.js and AngularJs but my database is somewhere else (say abc.com).
I want to store image in mysql database at abc.com (Not saving images on heroku).
I have used text, blob, longblob datatype to store image from AngularJs using ng-file-upload (npm module). When i upload image, it is stored in database.
I have created a rest api on abc.com to fetch database values and consuming rest in node.js.
Now, I want to fetch image from database and display in html page. I have fetched database value from mysql -> abc.com -> node.js -> angularjs and tried angular-base64, atob and btoa to convert database value to show image, but i had no luck.
let _arrayBufferToBase64 = function (buffer) {
return $base64.encode(buffer);
};
let _arrayBufferToBase64 = function (buffer) {
console.log('_arrayBufferToBase64')
var binary = '';
var bytes = new Uint8Array(new Buffer(buffer, 'base64'));
// var bytes = new Uint8Array(buffer);
var len = bytes.byteLength;
console.log(len);
for (var i = 0; i < len; i++) {
binary += String.fromCharCode(bytes[i]);
}
return window.btoa(binary);
};
UtilService.fetchImage()
.then(function(res){
console.log(res);
if(res.success){
let data = res.data[0].profile_pic;
console.log(data);
$scope.img = 'data:image/png;base64,'+_arrayBufferToBase64(data);
// $scope.img = 'data:image/png;base64,'+data;
console.log($scope.img);
} else {
console.log('image not found');
$scope.alt = "Image is not found";
}
})
}
template: '<img class="img-responsive img-hover" ng-src={{img}} alt={{alt}}"/>'
When my database was in heroku, above code was working fine. But now i need some help.
Thanks in advance...
Found solution for my question and want to share with others.
My requirement was to send image from angularjs to nodejs, and from nodejs to abc.com (where my database is present).
From angularjs, I used ng-file-upload as:
<div class="col-sm-12">
<button class="col button btn btn-primary btn-sm" ng-model="$ctrl.imageFile" id="imageFile" name="imageFile" ngf-pattern="'image/*'" ngf-select ngf-accept="'image/*'" ngf-max-size="2MB" ngf-resize="{width: 512, height: 512, quality: 1}">Select/Change</button>
<p class="text-danger text-center" ng-show="profileImageForm.imageFile.$error.maxSize">
2MB is max size
</p>
<p class="text-danger text-center" ng-show="profileImageForm.imageFile.$error.pattern">
Select image
</p>
<button ng-show="!!$ctrl.imageFile" class="col btn btn-primary btn-sm" ng-click="$ctrl.uploadProfilePic($ctrl.imageFile)">Upload</button>
</div>
Upload.upload({
// request method is post
url: 'server-url',
data: { imageFile: $ctrl.imageFile },
headers: Utility.authHeader
}).then(function (resp) {
// ...
})
On server side (NodeJs):
app.post('server-url', , function (req, res) {
const formidable = require('formidable');
const form = new formidable.IncomingForm();
const base64Img = require('base64-img');
form.encoding = 'utf-8';
form.parse(req, function (err, fields, file) {
logger.debug(file);
if (!!file.imageFile && !!file.imageFile.path) {
const uploadedImagePath = file.imageFile.path // imageFile is form param name
logger.debug(uploadedImagePath); // image will be stored in temp folder on server
// convert image to base64 encoded string
base64Img.base64(uploadedImagePath, function (err, base64String) {
logger.debug(base64String);
// send base64String to abc.com and store in database
});
} else {
logger.debug("Image path is not available");
res.json({ success: false })
}
});
})
When i want to display stored image:
Fetch base64String from database and use as if it is image:
Utility.fetchImage()
.then(function(res){
$ctrl.img = res.data;
})
<img class="img-responsive img-hover" ng-src={{img}} />
I hope it will help you. I would be happy to know other alternatives as well.

Angularjs - open a PDF in a new tab : customize url

I want to display a pdf file in a new tab.
I retrieve the pdf from my server (J2EE/Spring MVC).
When I am getting the response I do :
ReportingLot.FicheStock.get({idLot:vm.lot.id}, function (response) {
var file = new Blob([response.data], {type: 'application/pdf'});
var fileURL = window.URL.createObjectURL(file);
var pdfFile = $sce.trustAsResourceUrl(fileURL);
window.open(pdfFile, '_blank');
});
The pdf displays in the new tab, but the url is :
blob:http://localhost:8080/9e8eb169-afff-4013-9a7a-04c2efdfb7e3
is there a way to custom this ur to make it more understable for the users?
Thanks.
[UPDATE]
Response.setHeader("Content-disposition", "inline; filename=\"ficheStock.pdf\"");
response.setContentType("application/pdf");
ServletOutputStream outputStream = response.getOutputStream();
baos.writeTo(outputStream);
outputStream.flush();

Download report from jsreport and angularjs

I'd like to know how could I make a report downloadable from my AngularJS Application?
The report is a .xlsx I can post the data, but the response is:
What I'd like is a downloadable file, or to open the .xlsx on Excel Online in other tab as in the preview.
How could I do that?
I usually recommend to create a hidden form and do plain http submit to jsreport /api/report. This is the most stable way and works across all browsers.
<form method='POST' target='_blank' action='/api/report' id='jsrForm'>
<input hidden='true' name='template[shortid]' value="41ucBgXKe"/>
<input hidden='true' name='data[foo]' value="Hello world"/>
<input hidden='true' name='options[Content-Disposition]' value="attachment; filename=myreport.pdf"/>
</form>
<script>
document.getElementById("jsrForm").submit();
</script>
Do you have control over the response? If so, add the content-disposition header and MediaType header to the response:
For System.Net.Http.HttpResponseMessage
var response = new HttpResponseMessage{Content = ...........}
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") {
FileName = "mydoc.xlsx"
};
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
For System.Net.WebClient
var client = new WebClient();
client.Headers.Add("Content-disposition", "attachment");
client.Headers.Add("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");

Read barcode via camera in an ASP.NET MVC 5 Application

I have created a web site with ASP.NET MVC 5. This web site is also available on mobile devices as a web app. But now I want to add the possibility for the user to scan barcodes with the mobile camera when they are using the app on their mobiles. Of course there are tools like phonegap that enable read barcodes, but the point is I want to add this functionality in my ASP.NET MVC 5 project.
So is there a way to read barcodes via the mobile camera in ASP.NET MVC 5?
I have solved this issue and here is the solution:
In the view (Index.chtml):
<form>
<input type="file" class="upload" size="45" name="file" id="file">
</form>
It is important to write the <input type="file"...> in a form tag.
Next I use the javascript. I use it because I want to call the controller as soon as the Browse button is clicked. You can use a submit button, too.
Javascript:
$('#file').on("change", function () {
for (i = 0; i < $('form').length; i++) {
if ($('form').get(i)[0].value != "") /* get the file tag, you have to customize this code */
{
var formdata = new FormData($('form').get(i));
CallService(formdata);
break;
}
}
});
function CallService(file) {
$.ajax({
url: '#Url.Action("Scan", "Home")',
type: 'POST',
data: file,
cache: false,
processData: false,
contentType: false,
success: function (barcode) {
alert(barcode);
},
error: function () {
alert("ERROR");
}
});
}
Next we have have analyse the image in the server and read the barcode of it. I am using the Aspose.BarCode Library:
HomeController.cs
public JsonResult Scan(HttpPostedFileBase file)
{
string barcode = "";
try
{
string path = "";
if (file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
path = Path.Combine(Server.MapPath("~/App_Data"), fileName);
file.SaveAs(path);
}
// Now we try to read the barcode
// Instantiate BarCodeReader object
BarCodeReader reader = new BarCodeReader(path, BarCodeReadType.Code39Standard);
System.Drawing.Image img = System.Drawing.Image.FromFile(path);
System.Diagnostics.Debug.WriteLine("Width:" + img.Width + " - Height:" + img.Height);
try
{
// read Code39 bar code
while (reader.Read())
{
// detect bar code orientation
ViewBag.Title = reader.GetCodeText();
barcode = reader.GetCodeText();
}
reader.Close();
}
catch (Exception exp)
{
System.Console.Write(exp.Message);
}
}
catch (Exception ex)
{
ViewBag.Title = ex.Message;
}
return Json(barcode);
}
}
Now the decoded barcode is returned to the view.

Save PDF file loaded in iframe

I am trying to save a pdf file that is loaded in an iFrame. There is by default a button in the iFrame to save the file but I want an extra button (outside the iFrame) to save the file.
<iframe id="labelFrame" src="loadedFile.pdf"></iframe>
<button id="savePDF">Download File</button>
In javascript:
$('#savePDF').click(function(){
var save = document.getElementById('labelFrame');
//Save the file by opening the explorer for the user to select the place to save or save the file in a default location, how do I do this?
}
What is the best way to reach this?
I needed an answer to this question as well and found a solution.
When displaying a PDF in an IFrame the browser will render it in an <embed> element and from there we cant use it in javascript as far as i know.
We'll need to use XMLHttpRequest to get the PDF from a server as a Blob object only then we can both display it and save it using javascript.
var iframe = document.getElementById('labelFrame'),
saveBtn = document.getElementById('savePDF'),
pdfUrl = 'loadedFile.pdf';
var xhr = new XMLHttpRequest();
xhr.open("GET", pdfUrl);
xhr.responseType = 'blob'; // <- important (but since IE10)
xhr.onload = function() {
var blobUrl = URL.createObjectURL(xhr.response); // <- used for display + download
iframe.src = blobUrl
saveBtn.onclick = function() {
downloadBlob(blobUrl, 'myFilename.pdf');
}
};
xhr.send();
The xhr.onload function will set to src of the iframe and add the onclick handler to the save button
Here is the downloadBlob() function that i've used in the example
function downloadBlob(blobUrl, filename) {
var a = document.createElement('a');
a.href = blobUrl;
a.target = '_parent';
// Use a.download if available. This increases the likelihood that
// the file is downloaded instead of opened by another PDF plugin.
if ('download' in a) {
a.download = filename;
}
// <a> must be in the document for IE and recent Firefox versions,
// otherwise .click() is ignored.
(document.body || document.documentElement).appendChild(a);
a.click();
a.remove();
}

Resources