Files are not received when sending form data to the server - asp.net

I am trying to send form data to my server (Asp.net server), but when debugging the server only the typed information is received, but the files are not there.
This is my html page: (http://pastebin.com/KZERsepn)
<template>
<ai-dialog>
<ai-dialog-body>
<div>
<span>character name</span>
<input type="text" value.bind="user.name" />
</div>
<div>
<span>Youtube url:</span>
<input type="text" value.bind="user.YoutubeUrl" />
</div>
<div>
<span>ProfileImage:</span>
<input type="file" file.bind="user.ProfileImage" />
</div>
<div>
<span>CoverImage:</span>
<input type="file" file.bind="user.CoverImage" />
</div>
</ai-dialog-body>
<ai-dialog-footer>
<button click.trigger="controller.cancel()">Cancel</button>
<button click.trigger="controller.ok(user)">Ok</button>
</ai-dialog-footer>
</ai-dialog>
and this is how i am posting the data:(http://pastebin.com/7bVHZthE)
createUser(user) {
let model = new FormData();
model.append('Name', user.Name);
model.append('YoutubeUrl', user.YoutubeUrl);
model.append('ProfileImage', user.ProfileImage);
model.append('CoverImage', user.CoverImage);
return this.client.fetch('/api/createUser', {
method: "post",
body: model,
headers: {
'Access-Controll-Allow-Origin': '*',
'Accept': 'application/json'
}
});
}
But only the user.name and user.youtubeurl properties are sent to the server.

To post files, you must use a multipart/form-data
The trick to posting a multipart/form-data is (rather unintuitively) to force the content-type header to false. So try this:
return this.client.fetch('/api/createUser', {
method: "post",
body: model,
headers: {
'Content-type': '', // this is where the magic happens
'Access-Control-Allow-Origin': '*',
'Accept': 'application/json'
}
});

Related

Multiple submit button fail to find the handler method in asp.net core 3.1 razor page application

I have a single form which has two button one to upload image using ajax call & other is main submit button which saves all the data.
I am still very new to asp.net core and trying different thing to learn asp.net core with razor page.
I read lot of article about multiple form submit but most of then where using two form with submit button for each.
My issue is when i hit the submit button it fails to find the handler method, after full days troubleshoot nothing worked and last few article point to error/failure to antiforgery, i not sure how to implement it in below code as i tried few but they gave error may be article where old referencing core 2.2 etc example1 example2
I am not sure about the what exactly is causing the issue any help would be appreciate.
I am trying to upload Image using Ajax method in asp.net core Razor pages, I am main form in will all input fields are kept and with the form for Fileupload i am also added addition button which is for file upload using Ajax, When i hit the
<input type="submit" value="Upload Image" asp-page-handler="OnPostUploadImage" id="btnUploadImage" />
i want it to call OnPostUploadImage method in pageModel file but it alway goes to default OnPost method. when i rename the OnPost to OnPost2 nothing happend..
How can i call OnPostUploadImage() on button btnUploadImage click event.
When i hit click btnUploadImage it generates following error on browser console
Error in FF
XML Parsing Error: no root element found Location:
https://localhost:44364/Admin/News/NewsCreate?handler=OnPostUploadImage
Line Number 1, Column 1:
Error in Chrome
jquery.min.js:2 POST
https://localhost:44364/Admin/News/NewsCreateMultipleSubmit?handler=OnPostUpLoadImage
400 (Bad Request)
event though path looks fine but it cant find it as per error message
#page
#model BookListRazor.Pages.Admin.News.NewsCreateModel
#{
ViewData["Title"] = "News Create";
Layout = "~/Pages/Shared/_LayoutAdmin.cshtml";
}
<div class="border container" style="padding:30px;">
<form method="post" enctype="multipart/form-data">
<div class="text-danger" asp-validation-summary="ModelOnly"></div>
<input hidden asp-for="News.NewsImage" />
<input id="fileName" hidden value="" />
<div class="form-group row">
<div class="col-2">
<label asp-for="News.NewsHeading"></label>
</div>
<div class="col-10">
<input asp-for="News.NewsHeading" class="form-control" />
</div>
<span asp-validation-for="News.NewsHeading" class="text-danger"></span>
</div>
<div class="form-group row">
<div class="col-2">
<label asp-for="News.NewsImage"></label>
</div>
<div class="col-10">
#*<input asp-for="News.NewsImage" type="file" class="form-control" id="NewsImage">*#
#*Photo property type is IFormFile, so ASP.NET Core automatically creates a FileUpload control *#
<div class="custom-file">
<input asp-for="NewsImageForUpload" class="custom-file-input form-control">
<label class="custom-file-label">Click here to change photo</label>
<input type="submit" value="Upload Image" asp-page-handler="OnPostUploadImage" id="btnUploadImage" />
</div>
</div>
<span id="imageStatus" class="text-danger"></span>
<span asp-validation-for="NewsImageForUpload" class="text-danger"></span>
</div>
<div class="form-group row">
<div class="col-3 offset-3">
<input id="btnSave" type="submit" value="Create" class="btn btn-primary form-control" />
</div>
<div class="col-3">
<a asp-page="Index" class="btn btn-success form-control">Back to List</a>
</div>
</div>
</form>
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script src="https://cdn.ckeditor.com/4.14.0/full/ckeditor.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<script>
$(document).ready(function () {
$("#btnSave").addClass("disable-button");
$('.custom-file-input').on("change", function () {
var fileName = $(this).val().split("\\").pop();
$(this).next('.custom-file-label').html(fileName);
$("#fileName").val(fileName);
$("#btnSave").removeClass("disable-button");
});
if ($("#fileName").val() == "") {
//alert("Select Image...");;
}
});
</script>
</div>
#section Scripts{
<partial name="_ValidationScriptsPartial" />
<script>
$(function () {
$('#btnUploadImage').on('click', function (evt) {
console.log("btnUploadImage");
evt.preventDefault();
console.log("btnUploadImage after evt.preventDefault()");
$.ajax({
url: '#Url.Page("", "OnPostUploadImage")',
//data: new FormData(document.forms[0]),
contentType: false,
processData: false,
type: 'post',
success: function () {
alert('Uploaded by jQuery');
}
});
});
});
</script>
}
.cs file CODE
public async Task<IActionResult> OnPost()
{
if (ModelState.IsValid)
{
return Page();
}
else
{
return Page();
}
}
public IActionResult OnPostUploadImage()
{
//Some code here
}
Verify that you add the following code to the ConfigureServices method of startup.cs:
services.AddAntiforgery(o => o.HeaderName = "XSRF-TOKEN");
If you want to enter the OnPostUploadImage method, the url of the Ajax request needs to be changed to #Url.Page("", "UploadImage") without adding OnPost.
And the Ajax request should send the anti-forgery token in request header to the server.
Change your ajax as follow:
#section Scripts{
<partial name="_ValidationScriptsPartial" />
<script>
$(function () {
$('#btnUploadImage').on('click', function (evt) {
console.log("btnUploadImage");
evt.preventDefault();
console.log("btnUploadImage after evt.preventDefault()");
$.ajax({
url: '#Url.Page("", "UploadImage")',
//data: new FormData(document.forms[0]),
contentType: false,
processData: false,
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
type: 'post',
success: function () {
alert('Uploaded by jQuery');
}
});
});
});
</script>
}
You can refer to this for more details.

Multipart, how to send file correct

I'trying to send a Multipart form data, through Flutter but the response api can't get the image file. I created a Backend just to debug my call and I got this:
My code:
Map<String, String> fields = {
"label":'-Ll7XfpsPLd_w5kz-D0m'
};
MultipartRequest request = MultipartRequest(
'POST',
Uri.parse(url),
);
request.fields.addAll(fields);
request.files.add(
MultipartFile.fromBytes(
'image',
imagem.readAsBytesSync(),
contentType: MediaType('image', 'jpeg'),
)
);
return request.send();
The server answer:
received fields:
{ label: [ '-Ll7XfpsPLd_w5kz-D0m' ],
image:
[ '\M-o\M ... A LOT OF DATA]}
Then a made a HTML page just to test:
<form method="POST" enctype="multipart/form-data" action="http://172.20.10.2:5002/upload" >
<input type="text" name="zava" value="Zava" /> <br />
<input type="file" name="image" /> <br />
<input type="submit" /> <br />
</form>
And received de server answer:
received fields:
{ zava: [ 'Zava' ] }
received files:
{ image:
[ { fieldName: 'image',
originalFilename: 'Grifo.png',
path: '/tmp/0wvX_w8W5Mw_7flqIdK0b1xX.png',
headers: [Object],
size: 114862 } ] }
What's wrong with my code? Why de Multipart does not send the file as a file?
I discovered that if you pass the optional param filename of the MultipartFile the request works correctly.
Just have to do something like this:
MultipartFile.fromBytes(
'image',
imagem.readAsBytesSync(),
contentType: MediaType('image', 'jpeg'),
filename: 'dummy.jpg'
)
I had opened a bug on flutter about the request without filename (if must be repaired or the documentation changed)...

Large file streaming confusion

I want to handle large files in my application and microsoft documentation about File Uploads looks so bizarre. Why would I need MultipartReader whereas I would simply achieve what I want with the following:
#model SampleVM
<form method="post" enctype="multipart/form-data">
<input asp-for="Prop1" />
<input asp-for="Prop2" />
<input type="button" value="Ok" onclick="post();"/>
</form>
#section Scripts{
<script>
function post() {
var formData = new FormData();
formData.append('Prop1', $('#Prop1').val());
formData.append('Prop2', $('#Prop2')[0].files[0]);
$.ajax({
url: '#Url.Action("Index")',
type: 'POST',
processData: false,
contentType: false,
data: formData
});
}
</script>
}
and in the controller I can simply get the stream with
var stream = vm.Prop2.OpenReadStream()
and do whatever I want. What does Microsoft documentation achieve with that spaghetti code that I don't with this simple sample?

Fetch data from HTTP POST with CURL

i'm new with curl
I want to try fetch simple text from html input using curl and send it to another website using simple JSON
this is the simple html code i make
<form action="http:test.com" method="post">
<input type="text" id="text">
<input type="submit" value="submit">
</form>
is there a way to do it?
Thank you!
Since you need to fetch the data from Slack, the nice way is to use AJAX to post the data. The following JS codes are modified based on achavez's gist: Post to Slack using javascript and use jQuery.ajax.
<form action="http:test.com" method="post" id="the-form">
<input type="text" id="text">
<input type="submit" value="submit">
</form>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$('#the-form').submit(function(e) {
e.preventDefault();
var url = "http:test.com"; // Webhook URL
var text = $('#text').text(); // Text to post, get from your form
$.ajax({
data: 'payload=' + JSON.stringify({
"text": text
}),
dataType: 'json',
processData: false,
type: 'POST',
url: url
}).done(function(data) {
// do whatever you want with `data`, `data` is the response
});;
});
</script>

Use AJAX to submit data from HTML form to WebMethod

So I'm taking in data from an HTML form and then using AJAX to send the data to a web method to then be sent to a sqlite database, but my AJAX call is failing. What did I mess up? Am I doing it correctly?
HTML Form
<form id="addForm" >
<input type="text" name="playername" id="playername" placeholder="Player"/>
<input type="text" name="points" id="points" placeholder="Points" />
<input type="text" name="steals" id="steals" placeholder="Steals" />
<input type="text" name="blocks" id="blocks" placeholder="Blocks" />
<input type="text" name="assists" id="assists" placeholder="Assists" />
<input type="text" name="mpg" id="mpg" placeholder="MPG" />
<input type="text" name="shotpct" id="shotpct" placeholder="Shot %" />
<input type="text" name="threepct" id="3pct" placeholder="3 %" />
<input type="button" value="add player" id="addbtn" name="addbtn" />
</form>
AJAX
$("#addbtn").click(function () {
var form = $("#addForm").serializeArray();
$.ajax({
type: 'POST',
url: "players.aspx/addRow",
data: JSON.stringify(form),
dataType: 'json',
success: function () {
alert('success');
},
error: function () {
alert('failure');
}
});
});
and the web method(not finished, was just testing to see if I was getting data)
[WebMethod]
public static void addRow(object form)
{
var stuff = form;
}
I'm still learning how to use a lot of this stuff so any help will be greatly appreciated.
Replace
type: 'POST',
with
method: 'POST',
dataType: 'json'
is not needed since you're not receiving data back. The data returned from the server, is formatted according to the dataType parameter.
Also remove JSON.stringify(form),this is already done with the .serialize();
replace
JSON.stringify(form)
with
$('form').serializeArray()
So you will have:
$("#addbtn").click(function () {
var form = $("form").serializeArray();
$.ajax({
type: 'POST',
url: "players.aspx/addRow",
data: form,
dataType: 'json',
success: function () {
alert('success');
},
error: function () {
alert('failure');
}
});
});
If you still get error. there might be a server side problem in the page you are calling. to make sure of that I suggest you use the 'Advanced REST client' witch is a Google Chrome extension and you can test posting values with it and see the result.

Resources