I have try to upload a video to vimeo account directly from browser using api ,video details are created but file seems to corrupted/upload not happens.This is my sample code.
var file = $(this).prop("files")[0];
var formData = new FormData();
formData.append("file_data", file);
$.ajax({
url: "https://api.vimeo.com/me/videos/",
type: "post",
data: formData,
headers: {
"Authorization": "Bearer -----",
},
processData: false,
mimeType: "multipart/form-data",
contentType: false,
}).done(function (response) {
// Do something
}).complete(function (response) {
// Do something
}).fail(function (e) {
// Do something
});
vimeo video listing shows blank thumbnail
enter image description here
Try this piece of code. I have made some changes here:
var file = $(this).prop("files")[0];
var formData = new FormData();
formData.append("file_data", file);
$.ajax("https://api.vimeo.com/me/videos/", {
type: "POST",
headers: {
"Authorization": "Bearer -----",
},
data: formData,
contentType: "multipart/form-data", // changed this
dataType: "json",
crossDomain: true // for CORS policy error
}).done((response) => {
// Do something
}).fail((error) => {
// Do something
}).complete(() => {
// Do something
});
I have chaged contentType and removed mimeType. I've also removed un-necessary processData field.
Related
I've got an odd thing happening. On my index page I've got an ajax call that grabs a parameter off of an SVG and then hits the following code:
public async Task<IActionResult> OnPostStateClickAsync(string state)
{
HttpContext.Session.SetObject("CurrentFilters", SearchFilters);
SearchFilters.State = state;
return RedirectToPage("/Search");
}
I'm able to attach a debugger and see everything is working fine behind the scenes. The problem, the UI doesn't ever update and take me to the Search page. If I manually navigate there all the data is loaded and everything is fine.
Not seen this behavior before and I've used the same code in previous projects.
Here is the AJAX call in case it's relevant:
$(document).ready(function () {
$('path').click(function () {
var stateParameter = $(this).attr('id');
$.ajax({
type: "POST",
url: '/Index?handler=StateClick&state=' + stateParameter,
//data: searchTitle,
contentType: "application/json; charset=utf-8",
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
dataType: "json"
}).done(function (data) {
console.log(data.result);
location.reload();
});
});
});
You can change your code like bellow.
Action:
public async Task<IActionResult> OnPostStateClickAsync(string state)
{
//...
return new JsonResult(new { redirectToUrl = "/Search" });
}
In your Ajax:
$(document).ready(function () {
$('path').click(function () {
var stateParameter = $(this).attr('id');
$.ajax({
type: "POST",
url: '/Index?handler=StateClick&state=' + stateParameter,
//data: searchTitle,
contentType: "application/json; charset=utf-8",
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
dataType: "json",
success: function (response) {
window.location.href = response.redirectToUrl;
}
});
});
});
Test Result:
I want to upload a file using Axios but for that I need to use formData, my problem is that when I am using formData the data are not send at all.
Here is my code without formData, its working fine all the data are sent :
axios({
method: 'post',
url: jsonurl,
data: {
session_id: '123',
},
headers: {
'Content-Type': 'multipart/form-data',
}
})
.then((value) => {
console.log(value); // return in console : status 200 and config: data: session_id: "123" ...
})
.catch(err=>console.error(err));
Same code with formData (no data sent, $_GET['id'] doesnt exist) :
const formData = new FormData();
formData.append('session_id', '123');
axios({
method: 'post',
url: jsonurl,
formData,
headers: {
'Content-Type': 'multipart/form-data',
}
})
.then((value) => {
console.log(value); // return in console : status 200 but config: data: FormData {}
})
.catch(err=>console.error(err));
No data sent, return in console status 200 but config: data: FormData {} (so no data) and on backend $_POST['session_id'] doesnt exist, the form is sent (I get my jsonencode return) but there is no input data.
I dont catch any error either.
Finally I found the solution, my syntax was wrong, here is one who works :
var postResults = await axios.post(jsonurl,
formData,
{
headers: {
'Content-Type': 'multipart/form-data'
}
}
)
.then(function(value){
console.log(value);
return value;
})
.catch(function(error){
console.log(error);
});
I want to call a method from API Controller using AJAX. I have tried the following
I have added one hidden field in the view (like what we are doing in mvc controller)
<input type="hidden" id="GetShoppingCartUrl" value="#Html.Action("GetShoppingCartUrl","Cart")"/>
Then I have written ajax
function GetShoppingCart() {
debugger;
var url = $('#GetShoppingCartUrl').val();
$.ajax({
type: "get",
url: url,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
},
error: function () {
}
});
}
But here it is not getting the method, GetShoppingCartUrl from the API Controller CartController. I want to call that method, what changes make it happening ?
function GetShoppingCart() {
debugger;
var url = "Cart/GetShoppingCartUrl"
$.ajax({
type: "get",
url: url,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
},
error: function () {
}
});
}
you can directly put your actionlink in the url
Hope it helps. :)
Use this below code to get the url of your site in javascript and append it before the url in ajax call. e.g var url = baseUrl+ "Cart/GetShoppingCartUrl";
#{
string url = Request.Url.GetLeftPart(UriPartial.Authority) + Request.ApplicationPath;
if(url[url.Length-1]!='/')
{
url =url+ "/";
}
}
var baseUrl = '#url';
//alert(baseUrl);
I am new to MVC and I am trying to create an application with Knockout.js to send data back to the server dynamically. I am following an example i found at:
http://www.mytecbits.com/microsoft/dot-net/knockout-js-and-bootstrap-with-asp-net-mvc-part-2
It works perfectly off the site, but i am trying to send data to multiple models instead just one as in the example
The Knockout code used in the example to send the data back to the server is
var urlPath = window.location.pathname;
var CreateArticleVM = {
Title: ko.observable(),
Excerpts: ko.observable(),
Content: ko.observable(),
Test: ko.observable(),
btnCreateArticle: function() {
$.ajax({
url: urlPath + '/Create',
type: 'post',
dataType: 'json',
data: ko.toJSON(this),
contentType: 'application/json',
success: function(result) {
window.location.href = urlPath + '/';
},
error: function(err) {
if (err.responseText == "success") {
window.location.href = urlPath + '/';
}
else {
alert(err.responseText);
}
},
complete: function() {}
});
}
};
ko.applyBindings(CreateArticleVM);
How do i modify the above code to be able to accept a FormCollection? Or what is the best solution to my problem?
Thanks
Say your service is expecting more than one argument like following.
[HttpPost]
public String Create(ModelA modela, ModelB modelb)
{
//Server code.
}
In order pass the data for Create method from client side you need to form your postdata as follows.
$.ajax({
url: urlPath + '/Create',
type: 'post',
dataType: 'json',
data: {modela: { "modela data in the expected form" }, modelb : { "modelb data.." } },
contentType: 'application/json',
success: function(result) {
window.location.href = urlPath + '/';
},
.
.
.
.
});
I have been working on G drive API and doing upload, download delete and update of files and folders using JavaScript for windows 8 . The two problems which I encountered are;
When I upload a file or folder it gets uploaded with a title "UNTITLED" , can you tell me what I am doing wrong.? my request looks like this;
WinJs.xhr ({
url: 'https://www.googleapis.com/upload/drive/v2/files?uploadType=media',
type: "post",
headers: { "Authorization": "Bearer " + accessToken, },
data: { "mimeType": "application/vnd.google-apps.folder", "title": "sampleFolder2" } }).then
(function (success) {
var response = JSON.parse(success.response);
},
function (error) {
console.log(error);
});
When I download a file I get an encrypted or some unique type of response like if I download an JPEG image I get JFIF in response text. Can you please tell me why ? cant I get the file downloaded to my disk..?
Here is the complete function of insertion of file using media as uploadtype.
function insertFile(accessToken) {
var openPicker = new Windows.Storage.Pickers.FileOpenPicker();
openPicker.viewMode = Windows.Storage.Pickers.PickerViewMode.thumbnail;
openPicker.fileTypeFilter.replaceAll([".png", ".jpg", ".jpeg", ".txt"]);
openPicker.pickSingleFileAsync().then(function (file) {
if (file) {
var tMeta = {
title: file.name,
mimeType: file.contentType,
description: "xyz description."
};
WinJS.xhr({
url: 'https://www.googleapis.com/upload/drive/v2/files?uploadType=media',
type: "post",
headers: {
"Authorization": "Bearer " + accessToken,
'Content-Type': file.contentType,
'Title': file.name
},
body: tMeta,
}).then(function (success) {
var response = JSON.parse(success.response);
var file1 = response;
secondRequest(accessToken, file1 , file);
}, function (error) {
var x = 4;
});
}
});
}
function secondRequest(accessToken, file1,file) {
var x = 2;
var tMeta = {
title: file.name,
mimeType: file1.mimeType,
// description: "xyz description."
};
var URL = 'https://www.googleapis.com/upload/drive/v2/files/' + file1.id + '?uploadType=media'
WinJS.xhr({
url: URL,
type: "put",
headers: {
"Authorization": "Bearer " + accessToken,
'Content-Type': file1.mimeType,
'Title': file.name
},
body: tMeta,
data: MSApp.createFileFromStorageFile(file)
}).then(function (success) {
var secondResponse = JSON.parse(success.response);
var z = 3;
}), function (error) {
var x = 3;
}
}
If you would like to upload metadata with the file, you need to implement the multipart upload. It's explained on https://developers.google.com/drive/manage-uploads#multipart