Finding source of Image for PDF - javascript

so I am trying to figure out how I can change the image of this pdf template that was created for me on my Django App. I tried to change the img src to a direct link of the picture that I would like but the result turned out to be the same picture. What might be the best way to change the image?
Here is what appears in the template:
<td width="33%" style="margin-left: 20px;">
<img src="/site_media/css/output/images/logo1.jpg" width="100" style="display:inline; margin-right: 20px">
</td>
The JS file:
$scope.dw_receiving_receipt = function(elem, user, harvest_date) {
var data = {};
data.receiving_action_id = 'DASHBOARD';
data.seller_id = user;
data.harvest_date = moment(harvest_date, 'MM-DD-YYYY').format("YYYY-MM-DD");
data.plu_code = elem.plu_code.id;
data.seller_inventory = elem.selected_seller_inventory.seller_inventory;
$http.post('/inventories/print_receipt/', data, {
data: JSON
}).success(function(data, status, headers, config) {
$scope.success = true;
$scope.save_message = "Receiving receipt fetched successfully.";
var blob = new Blob([data], {
type: "application/pdf;"
});
saveAs(blob, 'receiving_receipt.pdf');
}).error(function(data, status, headers, config) {
$scope.error = true;
$scope.save_message = "Could not fetch receiving receipt.";
alert("Could not fetch receiving receipt.");
});
};
And the views.py:
def fetch_resources(uri, rel):
if uri == '/site_media/css/output/images/logo.jpg':
path = os.path.join(settings.BASE_DIR ,"accounts", "static", "accounts", "img","aggri_logo.jpg")
else:
path = os.path.join(settings.BASE_DIR ,"accounts", "static", "accounts", "img","Logo ALBA Organics.jpg")
return path
I have tried many different ways to changing the img src myself but its not budging.

Related

Get PDF from WebAPI and download from UI, but data gets corrupted

I call a Web API Controller from my UI which then gets a report from SSRS. It inserts the bytes in the content of the response and sends it to the UI where it gets downloaded as a PDF.
Inside my Web API Controller I write the report bytes to a test PDF file to inspect the contents of the pdf and to see if the data is correct, which it is. But when the PDF gets downloaded from my UI and I open it, I get a blank paged document. When I inspect the reponse content in Fiddler, I can see that the data is corrupted and doesn't match the test PDF file data.
Server side:
[HttpPost]
public HttpResponseMessage GetInstancePdf(InstancePdfModel model) {
var bytes = _digitalFormService.GetInstancePdf(model.ClientGuid, model.InstanceGuid, model.InstanceVersion);
File.WriteAllBytes(# "c:\temp\test.pdf", bytes);
var response = Request.CreateResponse();
response.Content = new ByteArrayContent(bytes);
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue(DispositionTypeNames.Inline) {
FileName = "file.pdf"
};
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
return response;
}
Client side:
$scope.downloadPdf = function(instance) {
$scope.isBusy = true;
digitalFormService.getInstancePdf(instance.instanceGuid, instance.instanceVersion).then(function(data) {
if (data.status === 200) {
const file = new Blob([data.data], {
type: data.headers("Content-Type")
});
if (navigator.appVersion.toString().indexOf(".NET") > 0) {
window.navigator.msSaveBlob(file, (`${instance.name} ${(new Date()).toLocaleString()}`).replace(",", ""));
} else {
//trick to download, store a file having its URL
const fileUrl = URL.createObjectURL(file);
const a = document.createElement("a");
a.href = fileUrl;
a.target = "_blank";
a.download = (`${instance.name} ${(new Date()).toLocaleString()}`).replace(",", "");
document.body.appendChild(a);
a.click();
}
} else {
debugger;
}
$scope.isBusy = false;
});
};
function getInstancePdf(instanceGuid, instanceVersion) {
var data = {
clientGuid: digitalFormConfig.clientToken,
instanceGuid: instanceGuid,
instanceVersion: instanceVersion
};
return $http({
url: digitalFormConfig.serverUrl +
"api/DigitalForm/GetInstancePdf",
dataType: "json",
data: data,
method: "POST"
}).then(function(response) {
return response;
},
function() {
return $q.reject("No Data");
});
}
I expect my downloaded PDF to be an informational document, matching the test PDF file saved inside the Web API Controller, but I get a blank document instead (same number of pages as test file, but blank).
I used Fiddler to inspect the response body. When I save the response body from within Fiddler as a pdf - everything is fine. So I am sure my server side code is correct. The problem must be somewhere on the client side.
Any help? Thanks.
I found the mistake. The bug was in the client side service. Code should look as follows:
function getInstancePdf(instanceGuid, instanceVersion) {
var data = {
clientGuid: digitalFormConfig.clientToken,
instanceGuid: instanceGuid,
instanceVersion: instanceVersion
};
return $http({
responseType: "arraybuffer",
url: digitalFormConfig.serverUrl +
"api/DigitalForm/GetInstancePdf",
dataType: "json",
data: data,
method: "POST"
}).then(function (response) {
return response;
},
function () {
return $q.reject("No Data");
});
}
The line responseType: "arraybuffer", was omitted previously.

angular ng-file-upload on PUT reader.result is undefined

I'm trying to update a module without uploading a new image. The problem is that if I do not upload a new image and instead try and use the image that i read back from the api then it says read.result is undefined when debugging. I think the reader is expecting an image stream and i'm giving it a url. Not sure how to fix this.
The API takes a DataURL which is the image, then stores it and puts image path/url in ImageURLPATH.
Code:
angular.module('Services.modulesPUT', [])
.service('modulesPUTSrvc', function (baseSrvc, $http,modulesGETSrvc,$rootScope,$state, myConfig) {
var fObject = {};
fObject.myForm = {};
fObject.details = {};
fObject.imgObject = {};
fObject.put = function ()
{
var imageData;
if (fObject.myForm.$valid)
{
var reader = new window.FileReader();
reader.readAsDataURL(fObject.details.ImageURLPath);
reader.onloadend = function () {
$rootScope.loading = true;
var result = $http({
method: "PUT",
dataType: 'json',
data: {
"DataURI": reader.result
},
url: myConfig.baseURL + 'odata/Modules(' + fObject.details.ModuleId + ')'
});
result.success(function (data) {
$rootScope.loading = false;
baseSrvc.toastMessage('Module has successfully been updated.');
$state.go('base.modules.get');
});
result.error(function (data) {
$rootScope.loading = false;
baseSrvc.returnError(data);
});
};
}
else
{
baseSrvc.toastMessage('Please input all required fields.');
};
};
return fObject;
});
<div class="md-block" flex-gt-sm>
<div class="imageUpload">
<md-tooltip md-direction="left">
Click here to select your image
</md-tooltip>
<div class="button"
required
ngf-select
ng-model="srvcObject.details.DataURI"
name="file"
ngf-pattern="'image/*'"
ngf-accept="'image/*'"
ngf-max-size="20MB"
><span ng-show="!srvcObject.details.DataURI">Select <br/> Course Image</span></div>
<div class="preview"
ngf-src="srvcObject.details.ImageURLPath"
ngf-background="srvcObject.details.ImageURLPath"></div>
</div>
</div>

How to upload image in Summernote Editor (AngularJs version)?

Can anyone tell me how to upload image in summernote editor (angularJs v.)?
My Code:
$scope.imageUpload = function(files) {
uploadEditorImage(files);
};
function uploadEditorImage(files) {
if (files != null) {
Upload.upload({
url: ROUTES.RESOURCESUPLOADFILE,
file: files
}).success(function(data, status, headers, config) {
var uploaded_file_name = data.file_name,
file_location = '/assets/uploads/'+uploaded_file_name;
$scope.editor.summernote('editor.insertImage', uploaded_file_name);
});
}
};
<summernote editor="editor" editable="editable" on-image-upload="imageUpload(files)" ng-model="lessonFormEditData.description" ></summernote>
Error:
TypeError: Cannot read property 'summernote' of undefined
Also "editable" parameter return undefined:
$scope.imageUpload = function(files) {
console.log($scope.editable); // undefined
};
Thanks!
You need to add code like above in after success.
var uploaded_file_name = data.file_name;
var file_path = '/assets/uploads/'+uploaded_file_name;
var editor = $.summernote.eventHandler.getModule();
editor.insertImage(vm.editable, file_path, uploaded_file_name);

Prevent blank page on bad file download

In our Angular JS application, I am downloading a file by simply calling window.location.
HTML:
<div class="row">
<div class="col-md-3 col-sm-4 col-xs-6" ng-repeat="file in files">
<div class="well well-sm truncate">
<a href="" title="Download {{file.FileName}}" ng-click="download(file)" ><b>{{file.FileName}}</b></a><br />
<small>{{(file.FileSize/1024)|number:2}} KB</small><br />
<i class="fa fa-trash CP text-danger pull-right" ng-show="mUser.Role>=20" title="Delete file" ng-click="deletefiles(file.AttID)"></i>
<small>Uploaded by {{file.AddedByName}} on {{file.Created|date:'dd MMM yyyy'}}</small>
</div>
</div>
</div>
Angular method:
$scope.download = function (ff) {
if (confirm('Download this file?')) window.location = "api/files/download?token=" + $rootScope.token + "&IDKey=" + ff.IDKey;
}
Web API Controller Method:
[HttpGet]
public HttpResponseMessage download(string Token, string IDKey)
{
HttpResponseMessage lResponse = new HttpResponseMessage(HttpStatusCode.OK);
// Validate request
Result lRes = UserClass.GetUserByToken(Token);
if (!lRes.IsSuccess)
{
lResponse.Content = new StringContent("User Token is invalid");
lResponse.StatusCode = HttpStatusCode.Forbidden;
return lResponse;
}
// Get File object
AttClass lAtt = AttClass.GetFile(IDKey);
if (!lAtt.IsOk)
{
lResponse.Content = new StringContent("Attachment ID Key is invalid");
lResponse.StatusCode = HttpStatusCode.NotFound;
return lResponse;
}
// Return file
lResponse.Content = new StreamContent(new FileStream(lAtt.GetFullPath(), FileMode.Open, FileAccess.Read));
lResponse.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = lAtt.FileName };
lResponse.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
return lResponse;
}
The file download works very well when Token and IDKey is valid. However, in other cases, the user is shown a blank page with a simple error message. Can I prevent this and just display an alert on the original page with the reason why the download failed?
PS: I do not want to use the HTML5 SaveAs functionality or filesaver.js.
you can try this
1- Did you try downloading file using iframe instead of the using
window.location
document.getElementById("myiframe").src="api/files/download?token=" + $rootScope.token + "&IDKey=" + ff.IDKey;
and the check the iframe body
document.getElementById('myiframe').contentDocument.body.innerHTML
Re EDIT
document.getElementById("myiframe").src="your url";
document.getElementById("myiframe").addEventListener("load",
function(){
console.log(this.contentDocument.contentType);
if(!(document.getElementById("myiframe").contentDocument.contentType=="application/octet-stream"))
alert("Downlaod Failed");
else
alert("Thank you for downloading");
});
Its very dificult to handle server response when you are using window.location.
You can use ajax call in angularJs to download or you can check your response too.
$http({
url: 'server/url',
method: "POST",
responseType: 'arraybuffer'
}).success(function (data, status, headers, config) {
//check your response here
//smaple code for excel download
var blob = new Blob([data], {type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"});
var objectUrl = URL.createObjectURL(blob);
var anchor = angular.element('<a/>');
anchor.attr({
href: objectUrl,
target: '_blank',
download: fileName + '_' + new Date().getTime() + '.xlsx'
})[0].click();
}).error(function (data, status, headers, config) {
});
`

AJAX Show Image after Upload

i working on uploading files using ajax for almost 3 hours and successfully managed to make it work, please check the code:
View
<div class="form-horizontal">
<div class="form-group">
#Html.Label("Choose Image(s)", new { #class = "control-label col-sm-3" })
<div class="col-sm-5">
<input type="file" name="UploadFile" id="UploadFile" accept=".png, .jpg, .gif" multiple />
</div>
</div>
<div class="form-group">
<div class="col-sm-5 col-sm-offset-3">
<input type="button" value="Save" id="save" class="add btn btn-primary" />
<div style="color:red">
#ViewBag.error
</div>
</div>
</div>
</div>
<div style="margin-top: 17px;">
#foreach (var item in Model.Content)
{
<div class="gallery">
<a href="#item.ImagePath" title="#item.Description" data-gallery>
<img src="#item.ThumbPath" alt="#item.Description" class="img-rounded" style="margin-bottom:7px;" />
</a>
<input type="button" class="delete btn btn-danger" value="Delete" data-picid="#item.PhotoId" />
</div>
}
</div>
Controller
[HttpPost]
public ActionResult Create(Photo photo)
{
var model = new Photo();
foreach (string file in Request.Files)
{
var fileContent = Request.Files[file];
if (fileContent.ContentLength == 0) continue;
model.Description = photo.Description;
var fileName = Guid.NewGuid().ToString();
var extension = System.IO.Path.GetExtension(fileContent.FileName).ToLower();
using (var img = System.Drawing.Image.FromStream(fileContent.InputStream))
{
model.ThumbPath = String.Format(#"/GalleryImages/thumbs/{0}{1}", fileName, extension);
model.ImagePath = String.Format(#"/GalleryImages/{0}{1}", fileName, extension);
// Save thumbnail size image, 100 x 100
SaveToFolder(img, fileName, extension, new Size(200, 200), model.ThumbPath);
// Save large size image, 800 x 800
SaveToFolder(img, fileName, extension, new Size(600, 600), model.ImagePath);
}
// Save record to database
model.CreatedOn = DateTime.Now;
db.Photos.Add(model);
db.SaveChanges();
}
return Json("File Uploaded Successfully");
}
JQuery/AJAX
<script type="text/javascript">
$('#UploadFile').on('change', function (e) {
var $this = $(this);
var files = e.target.files;
if (files.length > 0) {
if (window.FormData !== undefined) {
var data = new FormData();
for (var x = 0; x < files.length; x++) {
data.append("file" + x, files[x]);
}
$.ajax({
type: "POST",
url: '/Home/Create',
contentType: false,
processData: false,
data: data,
success: function (result) {
console.log(result);
//add code to refresh the gallery with the new uploaded image
},
error: function (xhr, status, p3, p4) {
var err = "Error " + " " + status + " " + p3 + " p4;
if (xhr.responseText && xhr.responseText[0] == "{")
err = JSON.parse(xhr.responseText).Message;
console.log(err);
}
});
} else {
alert("Error! This browser does not support file upload, please change your browser");
}
}
});
</script>
SavetoFolder
private void SaveToFolder(Image img, string fileName, string extension, Size newSize, string pathToSave)
{
// Get new image resolution
Size imgSize = NewImageSize(img.Size, newSize);
using (System.Drawing.Image newImg = new Bitmap(img, imgSize.Width, imgSize.Height))
{
newImg.Save(Server.MapPath(pathToSave), img.RawFormat);
}
}
NewImageSize
public Size NewImageSize(Size imageSize, Size newSize)
{
Size finalSize;
double tempval;
if (imageSize.Height > newSize.Height || imageSize.Width > newSize.Width)
{
if (imageSize.Height > imageSize.Width)
tempval = newSize.Height / (imageSize.Height * 1.0);
else
tempval = newSize.Width / (imageSize.Width * 1.0);
finalSize = new Size((int)(tempval * imageSize.Width), (int)(tempval * imageSize.Height));
}
else
finalSize = imageSize; // image is already small size
return finalSize;
}
but the problem is i have to refresh the browser to see the added image, what should i put in ajax on sucess upload to add the image dynamically without refreshing browser?
Since you are having option to upload multiple images I would suggest to go with below approach:
your controller now would look like:
[HttpPost]
public ActionResult Create(Photo photo)
{
List<Photo> model = new List<Photo>();
//create list of photo model
foreach (string file in Request.Files)
{
var fileContent = Request.Files[file];
if (fileContent.ContentLength == 0) continue;
var fileName = Guid.NewGuid().ToString();
var extension = System.IO.Path.GetExtension(fileContent.FileName).ToLower();
string thumpath,imagepath = "";
using (var img = System.Drawing.Image.FromStream(fileContent.InputStream))
{
model.Add(new Photo(){
Description=photo.Description,
ThumbPath = String.Format(#"/GalleryImages/thumbs/{0}{1}", fileName, extension),
ImagePath = String.Format(#"/GalleryImages/{0}{1}", fileName, extension),
CreatedOn=DateTime.Now
});
//fill each detail of model here
thumpath = String.Format(#"/GalleryImages/thumbs/{0}{1}", fileName, extension);
//separate variables to send it to SaveToFolder Method
imagepath = String.Format(#"/GalleryImages/{0}{1}", fileName, extension);
SaveToFolder(img, fileName, extension, new Size(200, 200), thumpath);
SaveToFolder(img, fileName, extension, new Size(600, 600), imagepath);
}
}
foreach(var md in model)
{
//loop again for each content in model
db.Photos.Add(md);
db.SaveChanges();
}
return Json(new {model=model },JsonRequestBehavior.AllowGet);
//return the model here
}
in ajax success you can create the image with the model returned values as below:
success: function (result) {
var model = result.model;
$(model).each(function (key,value) {
$('<img />').attr({
src: value.ThumbPath
}).appendTo("body");
//note you can append it to anywhere, like inside container or something
})
}
I would set the src attribute of the img tag usign jQuery in your success function:
success: function (result) {
$("img").attr('src' , '/path/to/your/img');
},
If you don't know the public path to your image on client side you can use the response object:
return Json("{ path : "+model.ImagePath+"."+fileName+"."+extension+"}");
There is a few possibilities, which to use depends on pictures size etc.
Personaly I (if images are not too big) would on server side convert image ot base64 and return it with ajax and display the data returned from server, of course it would need conversion as well.
Check out this article, i think i'll help you :)
Base64 encoded image

Categories