Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
Friday, July 1, 2016 10:54 AM
Hi,
Please tell me how can I send image info with JQuery to controller without submitting the form so that I can save the image in my computer in C#.
Now I can show the image but cannot save it.
<div style="padding-top: 15px; padding-bottom: 10px">
<form id="form1" runat="server">
<input type='file' id="imgInp" /><br />
<br />
<img id="imgDisplay" src="../../Images/noimage.png" alt="your image" style="width: 100px; height: 100px" />
</form>
</div>
JQuery
$(document).ready(function () {
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#imgDisplay').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
$("#imgInp").change(function(){
readURL(this);
});
});
This is my code that is showing the image perfectly.
Regards,
Sanhita
Friday, July 1, 2016 5:14 PM ✅Answered
Hi
You can do this using following
$(document).ready(function () {
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#imgDisplay').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
$("#imgInp").change(function(){
readURL(this);
var data = new FormData();
var files = $("#imgInp").get(0).files;
if (files.length > 0) {
data.append("imgInp", files[0]);
}
$.ajax({
type: 'POST',
url: '/Image/SubmitImage',
processData: false,
contentType: false,
data: data,
success: function (result) {
},
error: function (result) {
}
});
}); });
[HttpPost]
public string SubmitImage()
{
try
{
HttpPostedFileBase userImage = Request.Files["imgInp"];
}
}
Monday, July 4, 2016 9:39 AM ✅Answered
Hi Sir,
I suggest you could refer to the following code to upload image:
<input type="file" id="FileUpload1" />
<input type="button" id="btnUpload" value="Upload Files" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#btnUpload').click(function () {
// Checking whether FormData is available in browser
if (window.FormData !== undefined) {
var fileUpload = $("#FileUpload1").get(0);
var files = fileUpload.files;
// Create FormData object
var fileData = new FormData();
// Looping over all files and add it to FormData object
for (var i = 0; i < files.length; i++) {
fileData.append(files[i].name, files[i]);
}
// Adding one more key to FormData object
fileData.append('username', ‘Manas’);
$.ajax({
url: '/Home/UploadFiles',
type: "POST",
contentType: false, // Not to set any content header
processData: false, // Not to process data
data: fileData,
success: function (result) {
alert(result);
},
error: function (err) {
alert(err.statusText);
}
});
} else {
alert("FormData is not supported.");
}
});
});
</script>
Code in controller:
[HttpPost]
public ActionResult UploadFiles()
{
// Checking no of files injected in Request object
if (Request.Files.Count > 0)
{
try
{
// Get all files from Request object
HttpFileCollectionBase files = Request.Files;
for (int i = 0; i < files.Count; i++)
{
//string path = AppDomain.CurrentDomain.BaseDirectory + "Uploads/";
//string filename = Path.GetFileName(Request.Files[i].FileName);
HttpPostedFileBase file = files[i];
string fname;
// Checking for Internet Explorer
if (Request.Browser.Browser.ToUpper() == "IE" || Request.Browser.Browser.ToUpper() == "INTERNETEXPLORER")
{
string[] testfiles = file.FileName.Split(new char[] { '\\' });
fname = testfiles[testfiles.Length - 1];
}
else
{
fname = file.FileName;
}
// Get the complete folder path and store the file inside it.
fname = Path.Combine(Server.MapPath("~/Uploads/"), fname);
file.SaveAs(fname);
}
// Returns message that successfully uploaded
return Json("File Uploaded Successfully!");
}
catch (Exception ex)
{
return Json("Error occurred. Error details: " + ex.Message);
}
}
else
{
return Json("No files selected.");
}
}
Code from this articles:
http://www.c-sharpcorner.com/UploadFile/manas1/upload-files-through-jquery-ajax-in-Asp-Net-mvc/
http://www.technologycrowds.com/2015/10/jquery-mvc-upload-image-using-jquery.html
Best regards,
Dillion
Friday, July 1, 2016 11:06 AM
Hi,
Really unclear. Looks like you are trying maybe to post an image using an Ajax query? "so that I can save the image in my computer in C#" is weird. Do you mean on the web server or on a client computer? If this is the client computer you won't able to save the image without any user action.
I would suggest to get it right first and to enhance later ie just post the file as usual (ie for example http://haacked.com/archive/2010/07/16/uploading-files-with-aspnetmvc.aspx/ ) and enhance later once you are sure the basic stuff works fine (if even what you plan to do is possible).
It almost sounds like if you want the user to select a file and then save this file somewhere else on the client disk without even sending the file at all to the web server ???
Edit: also maybe https://cmatskas.com/upload-files-in-asp-net-mvc-with-javascript-and-c/ but for now I'm not 100% sure to get your exact intent (as for a developer "my computer" is both the client and the web server).
In short your question is just about how to upload a file to a web server using Ajax or do you have some more stuff in mind?
Friday, July 1, 2016 12:13 PM
Sorry for not making it clear. My task is.....
1. select an image from local computer using file upload control and show the image preview on screen in your MVC application.
2. Save the selected image in your client machine.
No 1 is done and perfectly fine. All I have to know how do I send the selected file in AJAX call to the controller so that I can save it in the local client computer.
Or is there a way where we can save the image to client computer by JQuery.
Friday, July 1, 2016 12:56 PM
Hi,
I have found code in one of your links. But this line is not accepted by C#
public async Task<JsonResult> UploadHomeReport(string id)
{
}
How can I get async class.
Friday, July 1, 2016 1:07 PM
Save the selected image in your client machine.
This is the part I don't get. The file is selected on the client machine and you want to save it back to the client machine (ie where the browser runs ???). Seems weird.
As told earlier you don't have access to the local hard drive and so you won't be able to save that directly (at best it would need to be posted to the server that will send back the file showing a confirmation to the user that will then be able to refuse or save this where he wants on his client disk).
Friday, July 1, 2016 1:17 PM
No I want to save the selected file to my project folder
Friday, July 1, 2016 1:29 PM
Ok so try for example https://cmatskas.com/upload-files-in-asp-net-mvc-with-javascript-and-c/ that uses Ajax to post the file to the web server (or the earlier link I posted if Ajax is not really required).
Friday, July 1, 2016 2:19 PM
Ya I have seen the link and wrote the code but in the controller method
public async Task<JsonResult> UploadHomeReport(string id)
it is showing error, not getting async,can you pls tell me how do I do that. I can get Task by System.Threading.Tasks
Friday, July 1, 2016 3:25 PM
And the error is ? You are using an earlier version that doesn't support the "async" keyword? IMO don't bother for now and just use public JsonResult UploadHomeReport(string id) to make first something that works and see if this is what you are looking after.
Once you get something that works, you'll always be able to enhance that if needed.