I have an input element that selects an image as follows:
HTML Code
<input type="file" id="uploadEditorImage" />
Javascript Code
$("#uploadEditorImage").change(function () {
var data = new FormData();
var files = $("#uploadEditorImage").get(0).files;
if (files.length > 0) {
data.append("HelpSectionImages", files[0]);
}
$.ajax({
url: resolveUrl("~/Admin/HelpSection/AddTextEditorImage/"),
type:"POST",
processData: false,
contentType: false,
data: data,
success: function (response) {
//code after success
},
error: function (er) {
alert(er);
}
});
And Code in MVC controller
if (System.Web.HttpContext.Current.Request.Files.AllKeys.Any())
{
var pic = System.Web.HttpContext.Current.Request.Files["HelpSectionImages"];
}
I want to save the selected image in a specific folder such as C\Temp. How can I go about doing that? Please help.
Thank you.
in your html:
<input type="file" id="FileUpload1" />
script:
$(document).ready(function () {
$('#FileUpload1').change(function () {
// Checking whether FormData is available in browser
if (window.FormData !== undefined) {
var data = new FormData();
var files = $("#FileUpload1").get(0).files;
console.log(files);
if (files.length > 0) {
data.append("HelpSectionImages", files[0]);
}
$.ajax({
url: '/Home/UploadFiles',
type: "POST",
contentType: false, // Not to set any content header
processData: false, // Not to process data
data: data,
success: function (result) {
alert(result);
},
error: function (err) {
alert(err.statusText);
}
});
} else {
alert("FormData is not supported.");
}
});
});
and backend:
[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("~/Content/"), 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.");
}
}
Related
Let me explain my problem, I have a LinkButton:
<asp:LinkButton ID="ForceUpdate" runat="server" OnClick="ForceUpdateBtn_Click" Text="<%$ Resources:Resource1, ForceUpdate%>" />
when I click on this LinkButton I set a command and then I check with JQuery if the button is clicked to show a message to wait until the machine is online to get the updated data and then disable the button:
window.setInterval(function () {
$.ajax({
async: true,
type: 'POST',
url: "../../WS/IOT_WebService.asmx/GetUpdateStatusStats",
data: { mccid: <%=mccIdToJavascript%>, language: '<%=currentCulture%>' }, // mccid: ID machine
cache: false,
beforeSend: function () {
},
success: function (txt) {
var string = xmlToString(txt);
string = string.replace("<?xml version=\"1.0\" encoding=\"utf-8\"?><string xmlns=\"http://tempuri.org/\">", "");
string = string.replace("<string xmlns=\"http://tempuri.org/\">", "");
string = string.replace("</string>", "");
console.log('check is ', <%=checkClick%>);
var check = <%=checkClick%>;
if (check) {
$('#status-force-update').text(string);
} else {
$('#status-force-update').text('----------');
}
},
error: function (xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
}
});
}, 3000);
Here's the method from the webservice where I check if in the db a certain data is set (CMD_Date_hour_Ok
!= null) to update the message that the machine is online and enable back the button.
[WebMethod]
public string GetUpdateStatusStats(string mccid, string language)
{
String strResponse = String.Empty;
CultureInfo currentCulture = new CultureInfo(language);
Thread.CurrentThread.CurrentCulture = currentCulture;
Thread.CurrentThread.CurrentUICulture = currentCulture;
try
{
MCC_Machine mcc = MCC_Machine.Retrieve(Convert.ToInt32(mccid));
CMD_Command cmd = CMD_Command.RetrieveByMCCType(mcc, 14); // 14 means that a ForceUpdate were launched
if (cmd == null)
{
cmd = CMD_Command.RetrieveByMCCType(mcc, 14);
}
if (cmd.CMD_Date_hour_Ok != null)
{
// machine is online
strResponse = Resources.Resource1.ForceUpdateStatsOnline.ToString();
}
else
{
// machine is offline
strResponse = Resources.Resource1.ForceUpdateStatsOffline.ToString();
}
}
catch
{
strResponse = Resources.Resource1.ForceUpdateStatsOffline.ToString();
}
return strResponse;
}
Now I need to disable the LinkButton and maybe change the color to grey to get the idea that it is disabled when I click it and enable it when the machine is online.
How can I do that?
Thank you
You need to change disabled attribute of ForceUpdate at every interval as following:
window.setInterval(function () {
$.ajax({
async: true,
type: 'POST',
url: "../../WS/IOT_WebService.asmx/GetUpdateStatusStats",
data: { mccid: <%=mccIdToJavascript%>, language: '<%=currentCulture%>' }, // mccid: ID machine
cache: false,
beforeSend: function () {
},
success: function (txt) {
var string = xmlToString(txt);
string = string.replace("<?xml version=\"1.0\" encoding=\"utf-8\"?><string xmlns=\"http://tempuri.org/\">", "");
string = string.replace("<string xmlns=\"http://tempuri.org/\">", "");
string = string.replace("</string>", "");
console.log('check is ', <%=checkClick%>);
var check = <%=checkClick%>;
if (check) {
$('#status-force-update').text(string);
} else {
$('#status-force-update').text('----------');
}
if(string =="Online"){ //check is machine online then set disable false
$("#<%=ForceUpdate.ClientID %>").attr("disabled", false);
}else{ // else mean machine is offline
$("#<%=ForceUpdate.ClientID %>").attr("disabled", true);
}
},
error: function (xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
}
});
}, 3000);
First i have now tried every page in here but nothing help. So this looks like all the others bus it isn't
i simply wants a file uploader where the image's are saved first and pass the image's ID back to a hidden input field as a string so i can find images again when the form is submitted.
no matter what i do i can't prevent the page for refreshing, which make the input field disappear :(
here is my code
HTML
<label for="file-uploader" class="custom-file-upload">
<i class="fa fa-cloud-upload fa-5x"></i><br /> Custom Upload
</label>
<input style="display: none" id="file-uploader" name="file" multiple="" type="file" />
<div id="input-wrapper">
Here comes all input fields
</div>
AJAX/JSON
$("#file-uploader").change(function () {
var formData = new FormData();
var totalFiles = document.getElementById("file-uploader").files.length;
for (var i = 0; i < totalFiles; i++) {
var file = document.getElementById("file-uploader").files[i];
formData.append("file-uploader", file);
}
$.ajax({
type: "POST",
url: '#Url.Action("Fileuploader", "Admin")',
data: formData,
dataType: 'json',
contentType: false,
processData: false,
success: function (data, e) {
$('#input-wrapper').append($('<input>').attr('type', 'hidden').attr('name', 'imagesId').attr('value', data.Id));
},
error: function(error) {
alert("error");
}
});
return false;
});
CONTROLLER
public JsonResult Fileuploader(int? pictureId)
{
db = new ApplicationDbContext();
var name = "";
if (pictureId != null)
{
var findImage = db.Imageses.Find(pictureId);
if (findImage == null) return Json(new { result = "Error" }, JsonRequestBehavior.AllowGet);
var filename = findImage.Url.Substring(10);
var path = Server.MapPath("~/Uploads/" + filename);
if (System.IO.File.Exists(path))
{
System.IO.File.Delete(path);
}
db.Imageses.Remove(findImage);
db.SaveChanges();
}
if (Request.Files.Count > 0)
{
for (int i = 0; i < Request.Files.Count; i++)
{
var file = Request.Files[i];
name = Guid.NewGuid().ToString();
var fileformat = Path.GetExtension(file.FileName);
var filename = name + fileformat;
var path = Path.Combine(Server.MapPath("~/Uploads/"), filename);
file.SaveAs(path);
}
for (int i = 0; i < Request.Files.Count; i++)
{
var file = Request.Files[i];
var img = new Images()
{
Filename = file.FileName,
DateCreated = DateTime.Now,
Url = "~/Uploads/" + name
};
db.Imageses.Add(img);
db.SaveChanges();
}
}
return Json(new { result = "Sucess", Id=name }, JsonRequestBehavior.AllowGet);
}
Is your #file-uploader sitting inside a form with an action method on it?
I would try taking the action attribute off, then adding the attribute to the form element in the success function of your ajax call.
I just disabled "enable Browser Sync" and it is working.
I have script for recording video
Here is code of it
var fileName;
stop.onclick = function () {
record.disabled = false;
stop.disabled = true;
window.onbeforeunload = null; //Solve trouble with deleting video
preview.src = '';
fileName = Math.round(Math.random() * 99999999) + 99999999;
console.log(fileName);
var full_url = document.URL; // Get current url
var url_array = full_url.split('/') // Split the string into an array with / as separator
var id = url_array[url_array.length - 1]; // Get the last part of the array (-1)
function save() {
$.ajax({
type: 'Post',
dataType: 'Json',
data: {
link: fileName,
id: id,
},
url: '#Url.Action("LinkWriter", "Interwier")',
success: function (da) {
if (da.Result === "Success") {
alert("lol");
} else {
alert('Error' + da.Message);
}
},
error: function (da) {
alert('Error');
}
});
}
I try to get url with this row var id = url_array[url_array.length - 1]; // Get the last part of the array (-1)
and with this code write to table filename
$.ajax({
type: 'Post',
dataType: 'Json',
data: {
link: fileName,
id: id,
},
url: '#Url.Action("LinkWriter", "Interwier")',
success: function (da) {
if (da.Result === "Success") {
alert("lol");
} else {
alert('Error' + da.Message);
}
},
error: function (da) {
alert('Error');
}
});
}
but it not works.
There is my Action method for it
[HttpPost]
public ActionResult LinkWriter(string link, int id) {
Link link_ = new Link
{
Link1 = link,
Interwier_Id = id,
};
db.Link.Add(link_);
db.SaveChanges();
return View();
}
But it not works. Where is my mistake?
UPDATE
As I understood not works this
function save() {
$.ajax({
type: 'Post',
dataType: 'Json',
data: {
link: fileName,
id: id,
},
url: '#Url.Action("LinkWriter", "Interwier")',
success: function (da) {
if (da.Result === "Success") {
alert("lol");
} else {
alert('Error' + da.Message);
}
},
error: function (da) {
alert('Error');
}
});
}
I have a problem here when I am trying to push data with angularjs controller. But what ever I do (IFormFile file) is always empty. There are only some examples with razor syntax but no examples how to do it with angular or jquery.
HTML:
<form class="form-body" enctype="multipart/form-data" name="newFileForm" ng-submit="vm.addFile()"><input type="file" id="file1" name="file" multiple ng-files="getTheFiles($files)"/></form>
Directive:
(function() {
'use strict';
angular
.module('app')
.directive('ngFiles', ['$parse', function ($parse) {
function fn_link(scope, element, attrs) {
var onChange = $parse(attrs.ngFiles);
element.on('change', function (event) {
onChange(scope, { $files: event.target.files });
});
};
return {
link: fn_link
};
}]);
})();
Controller
var formdata = new FormData();
$scope.getTheFiles = function ($files) {
angular.forEach($files, function (key, value) {
formdata.append(key, value);
});
};
vm.addFile = function () {
var xhr = new XMLHttpRequest();
xhr.open('POST', url, true);
xhr.setRequestHeader("Content-Type", "undefined");
xhr.send(formdata);
}
Asp.net core webapi:
[HttpPost]
public async Task<IActionResult> PostProductProjectFile(IFormFile file)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
....
return ...;
}
I have also tried to do it with formdata, as it is constructed when you post it with razor syntax. Something like this:
dataService.addFile(formdata, {
contentDisposition: "form-data; name=\"files\"; filename=\"C:\\Users\\UserName\\Desktop\\snip_20160420091420.png\"",
contentType: "multipart/form-data",
headers: {
"Content-Disposition": "form-data; name=\"files\"; filename=\"C:\\Users\\UserName\\Desktop\\snip_20160420091420.png\"",
'Content-Type': "image/png"
},
fileName: "C:\\Users\\UserName\\Desktop\\snip_20160420091420.png",
name: "files",
length : 3563
}
Also instead of formData to provide raw file as I wrote in comment. But still nothing happens
IFormFile will only work if you input name is the same as your method parameter name. In your case the input name is 'files' and the method parameter name is 'file'. Make them the same and it should work.
This is how to do it with angularjs:
vm.addFile = function () {
var fileUpload = $("#file").get(0);
var files = fileUpload.files;
var data = new FormData();
for (var i = 0; i < files.length ; i++) {
data.append(files[i].name, files[i]);
}
$http.post("/api/Files/", data, {
headers: { 'Content-Type': undefined },
transformRequest: angular.identity
}).success(function (data, status, headers, config) {
}).error(function (data, status, headers, config) {
});
}
And in web Api:
[HttpPost]
public async Task<IActionResult> PostFile()
{
//Read all files from angularjs FormData post request
var files = Request.Form.Files;
var strigValue = Request.Form.Keys;
.....
}
Or like this:
[HttpPost]
public async Task<IActionResult> PostFiles(IFormCollection collection)
{
var f = collection.Files;
foreach (var file in f)
{
//....
}
}
You can do it also with kendo upload much simpler:
$("#files").kendoUpload({
async: {
saveUrl: dataService.upload,
removeUrl: dataService.remove,
autoUpload: false
},
success: onSuccess,
files: files
});
From the answer of #Tony Steele.
Here is the code sample (Where to change/take care of)
.NET Core 3.1 LTS
[Route("UploadAttachment")]
[HttpPost]
public async Task<IActionResult> UploadAttachment(List<IFormFile> formFiles)
{
return Ok(await _services.UploadAttachment(formFiles));
}
AngularJS
var formFiles = new FormData();
if ($scope.files != undefined) {
for (var i = 0; i < $scope.files.length; i++) {
formFiles.append('formFiles', $scope.files[i]);
}
}
I'm trying to upload files using plupload and in MVC I have code like this:
public ActionResult Upload()
{
for (int i = 0; i < Request.Files.Count; i++)
{
var file = Request.Files[i];
file.SaveAs(AppDomain.CurrentDomain.BaseDirectory + "Uploads/" + file.FileName);
}
return Json(new { success = true }, JsonRequestBehavior.AllowGet);
}
and now I want to do same in web forms. I have added these code in my submit button click
protected void submitBtn_Click(object sender, EventArgs e)
{
for (int i = 0; i < Request.Files.Count; i++)
{
var file = Request.Files[i];
file.SaveAs(AppDomain.CurrentDomain.BaseDirectory + "Uploads/" + file.FileName);
}
}
and I need to send the success=true to my plupload javascript code to write these photos in my folder.
$(document).ready(function () {
var uploader = new plupload.Uploader({
runtimes: 'html5,flash,silverlight,html4',
browse_button: 'pickfiles',
container: document.getElementById('container'),
url: '/Admin.aspx',
flash_swf_url: '/Scripts/Moxie.swf',
silverlight_xap_url: '/Scripts/Moxie.xap',
filters: {
max_file_size: '10mb',
mime_types: [
{ title: "Image files", extensions: "jpg,gif,png" },
{ title: "Zip files", extensions: "zip" }
]
},
init: {
PostInit: function () {
document.getElementById('uploadfiles').onclick = function () {
uploader.start();
return false;
};
},
UploadProgress: function (up, file) {
_file_name = file.name;
$('#PhotoBox').val(_file_name);
console.log(file.name);
},
Error: function (up, err) {
alert("\nError #" + err.code + ": " + err.message);
}
}
});
uploader.init();
});
so Is there any equivalent of
return Json(new { success = true }, JsonRequestBehavior.AllowGet);
for asp.net Web Forms?
simply put
if (!IsPostBack) {
for (int i = 0; i < Request.Files.Count; i++)
{
var file = Request.Files[i];
file.SaveAs(AppDomain.CurrentDomain.BaseDirectory + "Uploads/" + file.FileName);
}
}
in your page load event and everything will okay