I am developing MVC application. I want to upload file with ajax post method,
$.ajax({
type: 'POST',
url: '#Url.Action("Add", "Media")',
data: formData,
contentType: false,
processData: false,
success: function (data) {
var result = JSON.parse(data);
if (result.Status !== 200) {
toastr.error('#Resources.Resource.Error_Unexpected');
return;
}
if (result.Result === "SUCCEED") {
toastr.success('#Resources.Resource.SuccessUpload');
window.location.reload();
return;
} else {
toastr.error('#Resources.Resource.Error_Unexpected');
}
},
error: function (error) {
console.log(error);
toastr.error('#Resources.Resource.Error_Unexpected');
return;
}
});
}
It works with small file. But when I try to upload 90MB pdf file it doesn't goes to controller. What is the problem.
Thanks in advance.
In your web.config file you need to increase maximum upload file setting. It affects the entire application.
<configuration>
<system.web>
<httpRuntime maxRequestLength="xxx" />
</system.web>
</configuration>
You need to place value in KB. The default is 4096 (= 4 MB).
Related
Lately I've been trying to solve an issue with no luck, basically I'm trying to submit a form to the server using AJAX, the form has files, so I'm using the FormData javascript object in JQuery 1.12. The data arrives to the server but in I way I don't know how to format it.
This is my AJAX function:
function saveMenu(id){
var formElement = document.getElementById("menu-form");
var formData = new FormData(formElement);
formData.append('_method', 'PUT');
$( "#form-wrapper" ).toggleClass( "be-loading-active" );
$.ajax({
type: 'PUT',
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
url: "{{url('myUrl')}}",
data: formData,
enctype: 'multipart/form-data',
processData: false,
success: function(response) {
toastr.success('Yai! Saved successfully!')
},
error: function(response) {
toastr.error('Oh oh! Something went really wrong!')
},
complete: function() {
$( "#form-wrapper" ).toggleClass( "be-loading-active" )
}
});
}
and when I perform a dd($request->all()); in my controller I get something like this:
array:1 [
"------WebKitFormBoundaryRCIAg1VylATQGx46\r\nContent-Disposition:_form-data;_name" => """
"_token"\r\n
\r\n
jtv4bnn8WQnP3eqmKZV3xWka2YOpnNc1pgrIfk0D\r\n
------WebKitFormBoundaryRCIAg1VylATQGx46\r\n
Content-Disposition: form-data; name="blocks[43][title]"\r\n
\r\n
...
Things I've tried:
Set the HTTP verb to POST. Same result.
Set the AJAX contentType: false, contentType: application/json. Empty response.
Remove enctype: 'multipart/form-data'. Same response.
Any help is appreciated.
This fixed it for me
data: form_data,
contentType: false,
processData: false,
processData: false prevents jQuery from parsing the data and throwing an Illegal Invocation error. JQuery does this when it encounters a file in the form and can not convert it to string (serialize it).
contentType: false prevents ajax sending the content type header. The content type header make Laravel handel the FormData Object as some serialized string.
setting both to false made it work for me.
I hope this helps.
$('#my-form').submit(function(e) {
e.preventDefault();
var api_token = $('meta[name="api-token"]').attr('content');
form_data = new FormData(this);
$.ajax({
type: 'POST',
url: '/api/v1/item/add',
headers: {
Authorization: 'Bearer ' + api_token
},
data: form_data,
contentType: false,
processData: false,
success: function(result,status,xhr) {
console.log(result);
},
error: function(xhr, status, error) {
console.log(xhr.responseText);
}
});
});
also remember to use $request->all(); $request->input() excludes the files
I've been trying to debug that for 2 hours and i found out that method PUT is not working with formData properly.
Try changing
type : "PUT"
into
method : "POST"
Then change your method on your backend from put to post and you'll see the difference.
I used below codes to test it
$("#menu-form").submit(function (){
var fd = new FormData();
fd.append('section', 'general');
fd.append('action', 'previewImg');
fd.append('new_image', $('.new_image')[0].files[0]);
$.ajax({
method : 'POST',
headers: {
'X-CSRF-TOKEN': '{{ csrf_token()}}'
},
url: "{{url('upload-now')}}",
data : fd,
contentType: false,
processData: false,
success: function(response) {
console.log(response);
},
});
return false;
});
And in my controller
public function test(Request $request){
dd($request->all());
}
Ill try to research more about this issue.
Laravel 7,
if use method PUT in ajax, you can follow
1. change method method: 'PUT' to method: 'POST'
2. add formdata.append with _method PUT like this example :
$('#updateBtn').click(function(e){
e.preventDefault();
var frm = $('#tambahForm');
frm.trigger("reset");
$('.edit_errorNama_kategori').hide();
$('.edit_errorGambar').hide();
var url = "/pengurus/category/"+$('#edit_id').val();
var formdata = new FormData($("#editForm")[0]);
formdata.append('_method', 'PUT'); //*** here
$.ajax({
method :'POST', //*** here
url : url,
data : formdata,
dataType : 'json',
processData: false,
contentType: false,
success:function(data){
if (data.errors) {
if (data.errors.nama_kategori) {
$('.edit_errorNama_kategori').show();
$('.edit_errorNama_kategori').text(data.errors.nama_kategori);
}
if (data.errors.gambar){
$('.edit_errorGambar').show();
$('.edit_errorGambar').text(data.errors.gambar);
}
}else {
frm.trigger('reset');
$('#editModal').modal('hide');
swal('Success!','Data Updated Successfully','success');
table.ajax.reload(null,false);
}
},
error: function (jqXHR, textStatus, errorThrown) {
alert('Please Reload to read Ajax');
console.log("ERROR : ", e);
}
});
});
its works for me
Finally I gave up trying to make it work and tried a more vanilla approach, I still don't know the reason why the request is formated like that, but the XMLHttpRequest() function works perfectly and the migration is not a big deal.
The equivalent of the function I posted about would be:
function saveMenu(action){
var formElement = document.getElementById("menu-form");
var formData = new FormData(formElement);
formData.append('_token', $('meta[name="csrf-token"]').attr('content'));
var request = new XMLHttpRequest();
request.open("POST", "{{url('myUrl')}}");
request.send(formData);
request.onload = function(oEvent) {
if (request.status == 200) {
toastr.success('Yai! Saved successfully!');
} else {
toastr.error('Oh oh! Something went really wrong!');
}
$( "#form-wrapper" ).toggleClass( "be-loading-active" );
};
}
Bit late, but;
This will solve your problem;
var formData = new FormData(document.getElementById('form'));
console.log(...formData);
var object = {};
formData.forEach(function (value, key) {
object[key] = value;
});
Then you can send this object to the server. This is much more readable and works great.
OR
You can simply send this directly;
JSON.stringify(Object.fromEntries(formData));
This is the newer approach.
And don't give up :-)
My app is an MVC .NET 4.0 application.
My application is fairly straightforward. I open an text file and uploaded it to be processed and returned as an excel file. This works as expected.
The excel file is returned via an actionresult controller. There are no errors. It works the way I want it to.
The problem is that when I call ajaxStart with blockUI it works. However, upon returning the file, the ajaxStop or ajaxSuccess is never fired to turn off the spinner after the file result is displayed with a message - do you want to open the file or save it or cancel.
I'm using jquery fileupload, blockUI and jquery 1.9.1.
$('#fileupload').fileupload({
dataType: 'json',
type: 'POST',
url: fileuploadpath,
autoUpload: true,
beforeSend: function () {
$.blockUI({
timeout: 0,
message: '<h1><img src="../images/ajax-loader.gif" /> Processing...</h1>'
});
},
complete: function() {
//$.unblockUI();
},
done: function (e, data) {
//$('.file_name').html(data.result.message.Name);
//$('.file_type').html(data.result.message.Type);
//$('.file_size').html(data.result.message.Length);
$('.file_msg').html(data.result.message.Error);
},
success: function (data) {
$.unblockUI();
$('.file_msg').html(data.result.message.Error);
}
});
and here is the basics of the file return in the action controller:
Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName);
return File(fileoutput, "application/vnd.ms-excel");
Everything works just great. The area I'm scratching over my head is - why isn't the spinner being turned off after the file return? Am I missing something? I've tried binding ajaxStop and ajaxStart to the document but that does not work. ajaxStart gets fired but upon the file return, ajaxStop is being ignored.
Remove the 'done' and 'complete' event and use this format for your ajax call:
$(document).ready(function() {
$('#fileupload').fileupload({
dataType: 'json',
type: 'POST',
url: fileuploadpath,
autoUpload: true,
timeout:60000,
beforeSend: function () {
$('#loader').show()
},
success: function (data) {
$('#loader').hide()
//$('.file_name').html(data.result.message.Name);
//$('.file_type').html(data.result.message.Type);
//$('.file_size').html(data.result.message.Length);
$('.file_msg').html(data.result.message.Error); //??? you are passing the error here
},
error: function(jqXHR, textStatus, errorThrown) {
$('#loader').hide()
if(textStatus==="timeout") {
alert("A timeout occurred");
} else {
alert("This is an other error");
}
}
});
});
NOTE: seen you have trouble with the blockUi, I have here used a other approach.
TIMEOUT:
I have set an extra parameter 'timeout' and set this to 60 sec. You coul set this to '0' which will be unlimited but it will be better practice to give it a limited value.
Place this in your HTML and give it a style of 'display:none' and an id.
<h1><img id="loader" src="../images/ajax-loader.gif" style="display:none"/> Processing...</h1>'
I am using the really nice Summernote Editor for a little webapp.
Instead of using the default inline base64 code for images I am storing the images in a folder.
I have that part working as intended. I am able to click the "image" icon and select an image and it will upload it to a folder on my server in its original type (jpg, png, gif).
The problem is that even though the image gets uploaded properly, Summernote does not add it to the editor ... so it doesn't show.
Here is the relevant code I am using:
$(function() {
$('.summernote').summernote({
lang: 'en-EN',
height: 500,
onImageUpload: function(files, editor, $editable) {
sendFile(files[0],editor,$editable);
}
});
function sendFile(file,editor,welEditable) {
data = new FormData();
data.append("file", file);
$.ajax({
url: "uploader.php",
data: data,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function(data){
alert(data);
editor.insertImage(welEditable, data);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus+" "+errorThrown);
}
});
}
});
The uploader.php file looks like this:
<?php
// A list of permitted file extensions
$allowed = array('png', 'jpg', 'gif','zip');
if(isset($_FILES['file']) && $_FILES['file']['error'] == 0){
$extension = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
if(!in_array(strtolower($extension), $allowed)){
echo '{"status":"error"}';
exit;
}
if(move_uploaded_file($_FILES['file']['tmp_name'],
'images/'.$_FILES['file']['name'])){
$tmp='images/'.$_FILES['file']['name'];
echo 'images/'.$_FILES['file']['name'];
//echo '{"status":"success"}';
exit;
}
}
echo '{"status":"error"}';
exit;
?>
Any ideas as to why the Summernote editor will not show the saved (stored) images in the editor?
Thanks
In the new version of summernote onImageUpload callback is called only with files argument. It means that editor is not available.
You can insert an image with:
$('.summernote').summernote("insertImage", url, filename);
In your case:
$('.summernote').summernote("insertImage", data, 'filename');
I did it using codeigniter may be this help someone.
$(function() {
$('.summernote').summernote({
onImageUpload: function(files, editor, $editable) {
sendFile(files[0],editor,$editable);
}
});
function sendFile(file,editor,welEditable) {
data = new FormData();
data.append("file", file);
$.ajax({
url: "http://localhost/fourm/media/editorupload",
data: data,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function(data){
editor.insertImage(welEditable, data);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus+" "+errorThrown);
}
});
}
});
You must use "callbacks: {}" method. like this:
$('.summernote').summernote({
height: 500,
tabsize: 4,
callbacks: {
onImageUpload: function(files, editor, $editable) {
console.log('onImageUpload');
sendFile(files[0],editor,$editable);
}
}});
Things tried:
commented lines regarding webdav
edited iis config file i.e added PUT,DELETE verbs
jQuery .support.cors = true;
Error: 405: method not allowed (in chrome debugger)
response is going to ajax error.
ajax call code:
jQuery.support.cors = true;
function CheckLogin() {
var user = { "UserName": $('#UserName').val(), "Password": $('#Passsword').val() };
user = JSON.stringify(user);
$.ajax({
url: 'http://localhost/MvcRazorClient/api/HomeApi/SignIn',
//here i changed the webapi route to api/controller/action
type: "PUT",
data: user,
async: false,
crossDomain: true,
contentType: "application/json",
dataType: 'json',
success: function (data) {
if (data == true) {
alert('true')
} else {
alert('false');
}
},
error: function () {
alert('er');
}
});
}
my api controller code:
[HttpPut]
public bool SignIn(User u)
//here i tried parameters as "dynamic u" and "HttpRequestMessage u". nothing worked
{
return true;
}
help please.
i didnt disable webDAV in iis .
path: Control Panel\All Control Panel Items\Programs and Features->iis->world wide web services->Common Http Features->(uncheck) webDAV
I am sending JSON object through following code.. Controller returning values in CSV format that should be provide promt to open or save as CSV file. I unable to understand that what exactly code should be write in success: function (result)
Link for Export
Html.ActionLink("Export", "", "", null, new { #onclick = "return exportData();"})
function exportData() {
var searchViewModel = getExLogSearchModelData();
var path = getAbsolutePath("ExclusionLog", "ExportData");
$.ajax({
url: path,
cache: false,
contentType: 'application/json; charset=utf-8',
dataType: 'html',
type: 'POST',
data: JSON.stringify(searchViewModel),
success: function (result) {
},
error: function (error) {
$("#voidcontainer").html("Error");
}
});
}
Controller ActionResult
public ActionResult ExportData(ExclusionLogSearchViewModel postSearchViewModel)
{
try
{
IEnumerable<ExclusionLogViewModel> exclusionLogData = null;
exclusionLogcData = this._workerService.GetExclusionLogData(postSearchViewModel);
return CSVFile(exclusionLogMembershipSyncData.GetStream<ExclusionLogViewModel>(), "ExclusionLogTables.Csv");
}
catch (Exception ex)
{
throw ex;
}
return null;
}
Can you please suggest how to do this?
I've hit the same problem and I didn't find a way to download file using $.ajax but I found an excellent JavaScript library that provides similar behavior:
https://github.com/johnculviner/jquery.fileDownload
You just need to invoke something like this:
$.fileDownload(path, {
httpMethod: 'POST',
data: JSON.stringify(searchViewModel),
success: function (result) {
},
error: function (error) {
$("#voidcontainer").html("Error");
}
});
And remember to create cookie in controller. In src/Common there is suitable action filter that do it for you.