I am sending byte array from backend and trying to open it with ajax and JS, I am always having corrupted PDf which cannot be opened.
me code is below.
$.ajax({
responseType: 'application\pdf',
sucess: function (response)
{
var blob=new blob([response]),{type:'application\pdf'};
window.navigator.msSaveOrOpen(blob);
}
});
any help would be much appreciated. thank you
Having the same issue with IE, ajax headers fixed the problem
$.ajax({
url: this.href,
cache: false,
xhrFields: {
responseType: 'blob'
},
success: function (data) {
var newBlob = new Blob([data], { type: "application/pdf" })
navigator.msSaveOrOpenBlob(newBlob, "something.pdf");
},
error: function (error) {
console.log(error);
}
});
First, set a break point in the success function, then try to use F12 developer tools to debug your code and make sure you could get the pdf blob. Then, use the window.navigator.msSaveOrOpenBlob() method to download pdf file.
Code as below:
var req = new XMLHttpRequest();
req.open("GET", "/44678.pdf", true);
req.responseType = "blob";
req.onload = function (event) {
var blob = req.response;
var newBlob = new Blob([blob], { type: "application/pdf" })
// IE doesn't allow using a blob object directly as link href
// instead it is necessary to use msSaveOrOpenBlob
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveOrOpenBlob(newBlob);
return;
}
};
More details, you could check this article.
Edit:please check your code, the Ajax method doesn't have the request url and have a spelling mistake at the success function.
Related
I have two audio files from RecordRTC both local & remote streams. Now I want to merge the two files into one file and upload it to the server via AJAX.
e.g. (audio1.webm) and (audio2.webm).
mediaRecorder.stopRecording(function() {
var blob = mediaRecorder.getBlob();
var fileName = getFileName('webm');
var fileObject = new File([blob], fileName, {
type: 'audio/webm'
});
var formData = new FormData();
formData.append('blob', fileObject);
formData.append('filename', fileObject.name);
$.ajax({
url: '{{ url('/') }}/save-audio',
data: formData,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function(response) {
console.log(response);
}
});
});
Thank you in advance.
UPDATE:
I made it this way instead of recorder.addStreams, and still I can get the recorded.
var remoteVideos = $('#remoteVideos video');
var el = [];
$.each($('#remoteVideos video'), function(index, val) {
el[index] = val.srcObject;
});
el.push(stream);
multiMediaRecorder = new MultiStreamRecorder(el);
You can use a similar library: MediaStreamRecorder. Then use MultiStreamRecorder and pass two streams as below,
recorder = new MultiStreamRecorder([localStream, remoteStream]);
You will get localStream from getUserMedia and remoteStream from onaddstream event listener.
You may want to just pass the audio tracks in the array. The rest of the things as it is. FFmpeg and file merging is not necessary.
I got it now by doing this, as below;
function onMediaSuccess(localStream) {
var remoteVideos = $('#remoteVideos video')[0];
multiMediaRecorder = new MultiStreamRecorder([localStream, remoteVideos.srcObject]);
multiMediaRecorder.ondataavailable = function (blob) {
// POST/PUT "Blob" using FormData/XHR2
var blobURL = URL.createObjectURL(blob);
console.log(blobURL);
};
multiMediaRecorder.start();
}
But now there's another problem, ondataavailable is called twice but the first video is playable and working properly, while the second video is playable but (less than one second) I think it might be corrupted.
Cheers!
I have a node.js server, which uses express-fileupload to accept images. Now I'm working on the function to upload an image. But I don't want to use < form > since I prefer xhtml request for various reasons, but mainly because I don't want to redirect the user, after he uploads an image.
I have tried reading the picture as dataURI, sending it to the server, decoding it and writing it to a file, which didnt work and seemed to resource intensive and laborious.
//I used the dataString from the callback method and wrote it to a file using fs.writeFile
function dataURItoimage(dataString, callback){
const atob = require("atob");
dataString.replace("data:image/jpeg;base64,", "");
dataString.replace("data:image/png;base64,", "");
atob(dataString);
callback(null, dataString);
}
//User side code
avatarInput.addEventListener("change", (e) => {
const reader = new FileReader();
reader.readAsDataURL(avatarInput.files[0]);
reader.onload = () => {
avatar = reader.result;
tosend.avatar = reader.result;
}
}, false);
uploadButton.onclick = () => {
var request = new XMLHttpRequest();
request.open("POST", "/avatarUpload");
request.setRequestHeader("Content-Type", "application/json");
var tosend = {avatar: ""};
tosend.avatar = avatar;
request.send(JSON.stringify(tosend));
}
Is there a better way to upload an image, which the user can select, to a node.js server?
You can try this example. It worked for me. I hope it can help you.
Sending dataURL throw Ajax request:
const dataURL = snapshotCanvas.toDataURL('image/png');
$.ajax({
url: 'http://localhost:3000/upload-image',
dataType: 'json',
data: { data: dataURL },
type: 'POST',
success: function(data) {}
});
Receiving request:
router.post('/', (req, res) => {
const base64 = req.body.data.replace(/^data:image\/png;base64,/, "");
fs.writeFileSync(`uploads/images/newImage.jpg`, base64, {encoding: 'base64'});
}
So I did it this way:
var request = new XMLHttpRequest();
request.open("POST", "/test");
var fd = new FormData();
fd.append("file", avatarInput.files[0]);
request.send(fd);
I created a FormData Object, appended the image, which the user chose in an input called "avatarInput", and send the object to the server.
On server side I used express-fileupload to access the file:
app.post("/test", (req, res) => {
if(req.files){
//With the follwing command you can save the recieved image
req.files.file.mv("./file.png", (err) => {if(err)throw err});
}
res.end();
});
I have an Angularjs 1.5.0 web application which should communicate with a REST-based web service that I had developed (using dropwizard & jersey) and tested that it works perfectly.
The REST web service method is like this:
#POST
#Path("/saveImage")
public Response saveImage(
#FormDataParam("imagefile") InputStream uploadedInputStream,
#FormDataParam("imagefile") FormDataContentDisposition fileDetail) {
// save image on server's file system and return OK
}
Scanned images are available to me by the scanner's local web server through a link like this: http://localhost:9980/thumb/random-generated-guid.jpg
In my angularjs code, I want to send the image which is available with the link above to my REST service.
Does anybody know how to do this?
I tried first saving the image as a blob and then send it to the web service. I could save the image using javascript's XMLHttpRequest but sending always fails.
Code for saving the image as Blob:
var xhr = new XMLHttpRequest();
xhr.open('GET', imageAddress, true);
xhr.responseType = 'blob';
var imageData = null;
xhr.onload = function(e) {
if (this.readyState === 4 && this.status === 200) {
// get binary data as a response
imageData = this.response;
var gatewayResponse = sendToGateway(imageData);
}
};
Code for sending the blob data:
var sendToGateway = function(imageDataBlob) {
var formdata = new FormData();
formdata.append('imagefile', imageDataBlob)
$.ajax({
url: 'http://localhost/eval/saveImage',
method: 'POST',
contentType: 'multipart/form-data; charset=UTF-8',
data: formdata,
dataType: 'json',
})
.done(function(response) {
$log.info("**************** response = " + response);
alert("response:\n" + response);
})
.fail(function(jqXHR, textStatus, errorThrown) {
$log.error("!!!! FAIL !!!!!!!!!");
alert("FAIL !!!!!!!");
})
.always(function(){
$rootScope.scannerInactive = false;
doStartPreviewUpdate();
});
};
Actually, the problem is when the sendToGateway(imageData); is called, I get the error:
TypeError: 'append' called on an object that does not implement
interface FormData.
value = jQuery.isFunction( value ) ? value() : ( value == null ? "" :
value );
oops, I found the problem. I should have added the following directives to the $.ajax() call.
processData: false,
contentType: false,
I'm trying to download and display an image that is returned from a wcf service using jQuery.ajax. I'm not able to work with the data I've received and I'm not sure why. I've tried a lot of things but nothing seems to work.
Here the service :
public Stream DownloadFile(string fileName, string pseudoFileName)
{
string filePath = Path.Combine(PictureFolderPath, fileName);
if (System.IO.File.Exists(filePath))
{
FileStream resultStream = System.IO.File.OpenRead(filePath);
WebOperationContext.Current.OutgoingResponse.ContentType = "application/x-www-form-urlencoded";
return resultStream;
}
else
{
throw new WebFaultException(HttpStatusCode.NotFound);
}
}
Here my ajax call :
$.ajax({
type: "GET",
url: apiURL + serviceDownloadFile.replace('{filename}', filename),
headers: headers,
contentType: "application/x-www-form-urlencoded",
processData : false,
success: function(response) {
var html = '<img src="data:image/jpeg;base64,' + base64encode(response) +'">';
$("#activitiesContainer").html(html);
},
error: function (msg) {
console.log("error");
console.log(msg);
}
});
Putting the url in a <img> tag does display the image properly, but since the service requires an authorization header, the page ask me for credentials each time.
So my question is, what to do this the response data so I can display it ? using btoa(); on the response displays an error :
string contains an invalid character
Thanks.
As suggested by Musa, using XMLHttpRequest directly did the trick.
var xhr = new XMLHttpRequest();
xhr.open('GET', apiURL + serviceDownloadFile.replace('{filename}', filename).replace('{pseudofilename}', fileNameExt), true);
xhr.responseType = 'blob';
xhr.setRequestHeader("authorization","xxxxx");
xhr.onload = function(e) {
if (this.status == 200) {
var blob = this.response;
var img = document.createElement('img');
img.onload = function(e) {
window.URL.revokeObjectURL(img.src); // Clean up after yourself.
};
img.src = window.URL.createObjectURL(blob);
document.body.appendChild(img);
}
};
xhr.send();
I want a server-side report to be generated from a javascript object and returned as a PDF. In one request.
I've tried a windows.location.href with the object in the query string, but the query string gets too long.
I've also tried a jQuery post with the object as attachment like this:
$.ajax({
url: "/SalesCalls/SalesCallReport/GetReport",
data: JSON.stringify(unmappedItem),
timeout: 10000,
type: 'POST',
contentType: 'application/json',
success: function (response, status, request) {
var disp = request.getResponseHeader('Content-Disposition');
if (disp && disp.search('attachment') != -1) {
var type = request.getResponseHeader('Content-Type');
var blob = new Blob([response], { type: type });
var URL = window.URL || window.webkitURL;
var downloadUrl = URL.createObjectURL(blob);
window.location = downloadUrl;
}
}
});
I stole the code in the success callback from another post on stackoverflow. It transfers the object to the server alright, but the output somehow doesn't work, I just get a blank pdf. I can see response contains the binary pdf, so I'm somehow missing a step.
The fact that this runs only on modern browsers is no problem.