How to PUT a binary file with javascript/jQuery to webdav? - ajax

How can I PUT a binary file, say an image with an HTTP PUT request to webdav? I already tried base64 encoding, but the file is broken.
$.ajax({
url: url + file,
data:base64content,
type: 'PUT',
crossDomain: true,
headers:{'content-type':'image/png'},
xhrFields:{withCredentials: true}
});

I've found a solution on this site:
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Sending_and_Receiving_Binary_Data
var oReq = new XMLHttpRequest();
oReq.open("POST", url, true);
oReq.onload = function (oEvent) {
// Uploaded.
};
var blob = new Blob(['abc123'], {type: 'text/plain'});
oReq.send(blob);

Related

JS/JSON file upload immutable dictionary is empty

I know, similar questions had been asked before.
All questions I found concerns upload within a form and need a submit button. This I don't want. I want upload to start after file selection is made (I'm aware of security risks).
Why is the contend of the file dictionary not send?
The button itself is created by JS:
downLoadBtn = document.createElement('INPUT');
downLoadBtn.id = 'downloadBtn';
downLoadBtn.type = 'file';
downLoadBtn.onchange = function(){upload()}
function upload(){
file = document.getElementById('downloadBtn')
console.log(file['files']['0'])
$.ajax({
type: "POST",
url: '/upload',
dataType : 'json',
data: JSON.file,
success: function (response){
console.log(response);
}
});
}
python:
#app.route('/upload', methods = ['POST'])
def upload():
if request.method == 'POST':
data = request.files
print(data)
return jsonify(data)
What I'm doing wrong?
You pass JSON.file as the data parameter which is not defined in the code you posted, it should be the file tat was selected.
Since your server side code expects multipart from data, you'll have to use a FormData object.
function upload(){
file = document.getElementById('downloadBtn')
console.log(file['files']['0'])
var fd = new FormData();
fd.append('file', file['files']['0']);
$.ajax({
type: "POST",
url: '/upload',
dataType : 'json',
data: fd,
contentType: false,
processData: false,
success: function (response){
console.log(response);
}
});
}

Uploading image file with ajax and receiving it with in the asp.net core mvc controller

I have tried all possible ways mentioned in this Solution, however didn't have any progress. Please help.
So my ajax request is as below:
function photoUploadConfirmed() {
event.preventDefault();
var files = $("#image")[0].files;
var formData = new FormData();
formData.append("file", files[0]);
console.log(files); // I just check here and in browser I can see file name and size
console.log(formData); // I expect to see the same here, but here it almost shows empty
$.ajax({
type: "POST",
url: "/Account/ChangeProfilePicture",
data: { image: formData }, // In the controller it receives IFormFile image
processData: false,
contentType: false,
success: function () {
console.log("Done");
$("#profilePhoto").val('');
$("#profPicUploadConfirm").attr("disabled", true);
},
error: function (errorMessage) {
console.log(errorMessage);
}
});
}
The ajax post request gets received by the controller's action, however the IFormFile image is always null.
[HttpPost]
public async Task<IActionResult> ChangeProfilePicture(IFormFile image)
{
// I do save here the image in the folder, but problem is that image==null
}
The ajax post request gets received by the controller's action,
however the IFormFile image is always null.
When the file is uploaded by formData append, the name at this time should be the same as "image" of the receiving parameter in action:
formData.append("image", files[0]);
And because you only need to pass the IFormFile to the action, in the data parameter of ajax, you only need to put the formData which appends the file named Image to it:
data: formData,
Change your js as follow:
function photoUploadConfirmed() {
event.preventDefault();
var files = $("#image")[0].files;
var formData = new FormData();
formData.append("image", files[0]);
console.log(files); // I just check here and in browser I can see file name and size
console.log(formData); // I expect to see the same here, but here it almost shows empty
$.ajax({
type: "POST",
url: "/Account/ChangeProfilePicture",
data: formData, // In the controller it receives IFormFile image
processData: false,
contentType: false,
success: function () {
console.log("Done");
$("#profilePhoto").val('');
$("#profPicUploadConfirm").attr("disabled", true);
},
error: function (errorMessage) {
console.log(errorMessage);
}
});
}
Here is the test result:
I had this same issue and even after updating the changes as suggested in previous answer, it didn't work for me.
Finally found the solution :
formData.append("fileInfo", fileInfo, "uploadedfile"); // uploadedfile is file name which at compile time converts to FormFile in Action method

Accept application/pdf in Ext.Ajax.request

I am using Ext.Ajax.request() to make an API call which produces MediaType.MULTIPART_FORM_DATA. This is being handled in the php layer which returns the object in
header("Content-Type: application/pdf");
echo $response;
The problem is, I am not able to handle the received object in the Ext.Ajax.request() since it always handles only Json objects by default.
I tried giving Headers, AcceptType in the request, but it always goes to the failure block.
Here is the code:
Ext.Ajax.useDefaultXhrHeader = false;
var responseText;
Ext.Ajax.request({
url: '/index.php/abc/xyz?value=' + value,
method: 'GET',
waitMsg: 'Printing Label',
contentType: 'application/octet-stream' //not sure,
responseType: 'blob' //not sure,
xhr2: false //not sure,
success: function (response) {
console.log("Success!!");
return "";
},
failure: function (response) {
//Always comes here. The API returns 200
console.log("Hi here in the error");
//Raw pdf gets printed
console.log(response.responseText);
}
});
but it always goes to the failure
For this you need to check in php side because may be something you have missed. I think may be this will help you readfile
Try with this code. Hope this will help/guide you to get required result.
Ext.Ajax.request({
url: '/index.php/abc/xyz?value=' + value,
method: 'GET',
waitMsg: 'Printing Label',
cors: true,
useDefaultXhrHeader: false,
withCredentials: true,
defaultHeaders: {
'Content-Type': 'application/octet-stream;'
},
timeout:0,//If don't know how time will take server to get the file then you can put 0. if you need
success: function(response) {
//In response you will directly get the octet-stream
//For showing pdf in front end side using blob url
var byteCharacters = atob(response.responseText),
len = byteCharacters.length,
byteNumbers = new Array(len),
key = 0,
byteArray,
blob,
contentType = 'application/pdf';
//insert charcter code in {byteNumbers}
for (; key < len; key++) {
byteNumbers[key] = byteCharacters.charCodeAt(key);
}
//convert {byteNumbers} into Uint8Array
byteArray = new Uint8Array(byteNumbers);
//create blob using {byteArray}
blob = new Blob([byteArray], {
type: contentType
});
// set {src} to {iframe}
window.open(window.URL.createObjectURL(blob), '_blank');
},
failure: function(response) {
//if somthing wrong in serverside then it will come in failure.
}
});
Hope this will also help you for this question as well.

Php FormData is null

I have a form with id: formC, on submit i call ajax:
var datiForm = new FormData();
var pos = [];
var i = 0;
posizioni.each(function () {
if($(this).find("input[type=checkbox]").is(":checked")){
pos[i] = $(this).find("input[type=checkbox]").data("id");
i++;
}
});
datiForm.append("nome",nome.val());
datiForm.append("cognome",cognome.val());
datiForm.append("email",email.val());
datiForm.append("telefono",telefono.val());
datiForm.append("dataNascita",dataNascita.val());
datiForm.append("titolo",titolo.val());
datiForm.append("ruolo",ruolo.find(":selected").data("ruolo"));
datiForm.append("sede",sede.find(":selected").data("sede"));
datiForm.append("posizione",pos);
datiForm.append("cvFile",$("#cvFile")[0].files[0]);
$.ajax({
type: "POST",
data: {datiForm: datiForm},
url: "saveCandidate.php",
processData: false,
contentType: false,
success: function (data) {
console.log(data);
},
error: function (data) {
var position = data;
}
});
I have a problem, on server $datiForm = $_POST["datiForm"]; is null why?
Moreover i have input file where i can select file pdf. I put it in FormData:
datiForm.append("cvFile",$("#cvFile")[0].files[0]);
Now on server i want to take file from $datiForm and save it into mysql as Blob is possible?
You specified the data field incorrectly, it should be just the form data object
data: datiForm,
also the way you add posizione is not going to work, each entry in yrh array has to be added individually
posizioni.each(function () {
if($(this).find("input[type=checkbox]").is(":checked")){
datiForm.append("posizione["+i+"]", $(this).find("input[type=checkbox]").data("id"));
i++;
}
});
Now on server i want to take file from $datiForm and save it into mysql as Blob is possible?
Yes
You'll need to specify the 'contentType' attribute to 'multipart/form-data' in order to upload files.

SummerNote onImageUpload converting server request to C# BASE64?

I have a C# MVC project where I will need to both use Summernote v0.8.2 as my WYSIWYG editor, along with exporting a PDF with jsPDF. I know that there are examples to make this work. My issue is that I need to custom resize/process the image that's inserted with summernote. Again, I know that you can capture this event using the onImageUpload callback. I'm having trouble correctly handing the incoming Request on the server to get the image and convert it into a BASE64 string. I would think this should be pretty easy, but I can't figure out what to do with the incoming Request to extract the Image. I've give you the whole process just to make sure you have enough info to help.
Here's my Summernote setup:
$('.summernote').summernote(
{
toolbar: [
['style', ['bold', 'italic', 'underline', 'clear']]
, ['fontname', ['fontname']]
, ['fontsize', ['fontsize']]
, ['color', ['color']]
, ['insert', ['picture']]
]
, callbacks: {
onImageUpload: function (image) {
uploadImage(image[0]);
}
}
}
);
Here's the AJAX call: FYI - I did change the data appended from image to file. Didn't change outcome.
function uploadImage(file, editor, welEditb) {
var data = new FormData();
//data.append("image", image);
data.append("file", file);
$.ajax({
url: '/home/UploadSummerNoteFile',
cache: false,
contentType: false,
processData: false,
data: data,
type: "post",
success: function (data) {
alert('display base64 data: ' + data);
//editor.insertImage(welEditable, url);
},
error: function (data) {
console.log(data);
}
});
}
My server method doesn't have any parameters, and I'm not sure how to extract just the FILE (IMAGE?) content. Once I get the actual file, I need to modify and change it (size, resolution, etc., which I can do), then convert it into BASE64 and send it back to the UI. So, my questions here this:
How do I get the file (image) from the request stream?
How do convert whatever this 'thing' is from above into BASE64?
I've used an online BASE64 converter for the image that I've been testing with so I know that my attempts haven't created a valid string.
Here's a partial example that I've found online, modified it (poorly) in an attempt to make work, which it doesn't:
byte[] buffer = new byte[Request.InputStream.Length];
Request.InputStream.Read(buffer, 0, buffer.Length);
string data = Encoding.Default.GetString(buffer);
string[] tokens = data.Split(',');
if (tokens.Length > 1)
{
// not sure what I'm doing, trying stuff. BOOOOM!
image = Convert.FromBase64String(tokens[1]);
base64 = Convert.ToBase64String(image);
//string fileName = DateTime.Now.ToString("yyyyMMddHHmmssffff") + ".png";
//string path = Path.Combine(#"D:\www\images", fileName);
//File.WriteAllBytes(path, image);
}
What do I need to do with the buffer or the data object? Where does the content of the file live in the request? Is it already converted when it was serialized for transport to the server? Also, assuming everything else gets completed, do I need to save the file to the server so it can be placed within Summernote's editor.insertImage(welEditable, url)? Thanks for your time and help!
Seems that I made this much harder than it needed to be. It's just a regular request, so extract the file from the request, and copy it to a memory stream. In this case I send back the BASE64 string to the calling function. Hopefully this helps others.
[HttpPost]
public JsonResult UploadFile()
{
var fileName = Request.Files[0].FileName;
var base64 = string.Empty;
using (var memoryStream = new MemoryStream())
{
Request.Files[0].InputStream.CopyTo(memoryStream);
var fileContent = memoryStream.ToArray();
base64 = Convert.ToBase64String(fileContent);
}
return Json(base64);
}
Here's the uploadImage ajax method changes: I create an instance of an IMG, and change the src to be the BASE64 value.
function uploadImage(file, editor, welEditb) {
var data = new FormData();
data.append("file", file);
$.ajax({
url: '/home/UploadSummerNoteFile',
cache: false,
contentType: false,
processData: false,
data: data,
type: "post",
success: function (data) {
var image = $('<img>').attr('src', 'data:' + file.type + ';base64,' + data);
$('.summernote').summernote("insertNode", image[0]);
},
error: function (data) {
console.log(data);
}
});
}

Resources