Uploading Document to App_Data - c#

I've currently got some working code that will upload a document to the App_data file, however I need to be able to differentiate the files uploaded if they have the same name. I want to do this by modifying the file name like so: ID" "Filename
I've had a few attempts to include this in the object thats passed to the controller but I can't find it stored anywhere (I presume that it gets stripped out when being passed?).
Here is my current code:
var files = $('#txtUploadFile')[0].files;
if (files.length > 0) {
if (window.FormData !== undefined) {
var data = new FormData();
for (var x = 0; x < files.length; x++) {
data.append("file" + x, files[x]);
}
// data.uploadName = task.Id + " " + files[0].name;
// File.filename = Id + " " + file.filename;
$.ajax({
type: "POST",
url: '../Document/UploadFiles/',
contentType: false,
processData: false,
//data: {'id': (nextRef + 1), 'fileLocation': files[0].name }, // THIS DOESN'T WORK
data: data, // THIS WORKS WITHOUT ANY OTHER VARIABLES
dataType: "json",
success: function (result) {
//alert(result);
},
error: function (xhr, status, p3, p4) {
var err = "Error " + " " + status + " " + p3 + " " + p4;
if (xhr.responseText && xhr.responseText[0] == "{")
err = JSON.parse(xhr.responseText).Message;
alert(log(err));
}
});
} else {
alert("This browser doesn't support HTML5 file uploads!");
}
}
[HttpPost]
public JsonResult UploadFiles()//string id, string fileLocation)
{
try
{
foreach (string file in Request.Files)
{
var hpf = Request.Files[file] as HttpPostedFileBase;
if (hpf.ContentLength == 0)
continue;
var fileContent = Request.Files[file];
if (fileContent != null && fileContent.ContentLength > 0)
{
// get a stream
var stream = fileContent.InputStream;
// and optionally write the file to disk
var fileName = Path.GetFileName(file);
var path = Path.Combine(Server.MapPath("~/App_Data/"), Path.GetFileName(hpf.FileName));
// Save the file
hpf.SaveAs(path);
}
}
}
catch (Exception)
{
Response.StatusCode = (int)HttpStatusCode.BadRequest;
return this.Json("Upload failed");
}
return this.Json("File uploaded successfully");
}

change from url: '../Document/UploadFiles/', to url: '#Url.Action("UploadFiles","YourController")
and in your controller
public class YourController:Controller{
[HttpPost]
publiction ActionResult UploadFiles(){
if (Request.Files != null && Request.Files.Count > 0)
{
string path=Server.MapPath("~/App_Data");
Request.Files[0].SaveAs(path + fileName);
return Json("File uploaded","text/json",JsonRequestBehavior.AllowGet);
}
return Json("No File","text/json",JsonRequestBehavior.AllowGet);
}
}

your html should be
<div><input type="file" name="UploadFile" id="fileupload" Class="fileupload" />
</div>
your ajax call should be
$.ajax({
type: "POST",
url: '/MyController/UploadFiles?id=' + myID,
contentType: false,
processData: false,
data: data,
success: function(result) {
console.log(result);
},
error: function (xhr, status, p3, p4){
});
//and your controller
[HttpPost]
public JsonResult UploadFiles(string id)
{
// whatever you want to that id
}
Happy coding...

Related

How do you pass perameter from a view to a controller function using ajax

I have a view with a button to call ajax but now need to include a parameter new { DNumber = item.DrawingNumber } and have that passed into the controller via ajax. What do I need to add to my code to make this work please?
view:
PDF
<script>
function OpenDrawingPDF() {
$.ajax({
url: "OpenDrawingPDF",
success: function () { alert("success"); }
});
return false;
}
</script>
Controller:
public void OpenDrawingPDF(string DNumber)
{
string Path = #"\\Serv1\Company\10 - Production\Production Drawings\CAD pdf\";
if (Directory.Exists(Path))
{
string Folder = DNumber.Substring(4, 2) + #"\";
System.Diagnostics.Process.Start(Path + Folder + DNumber + ".pdf");
}
}
Check the following approach. Provide your Id to your element holding a DBNumber and then access it from your function:
var dbNumber = $('#dbNumberItemId').val();
$.ajax({
url: "OpenDrawingPDF",
type: "Get", // I assume that you are sending get request
data: {
dbNumber: dbNumber
},
...
});
This was the solution that worked for me:
view:
<a id="myid" data-mydata1=#item.DrawingNumber href="javascript:" onclick="myPDF('tblCircuitDiagrams', this)">PDF</a>
<script>
function myPDF(table, value) {
var mydata = document.querySelector('#myid');
var dbNumber = value.dataset.mydata1;
$.ajax({
url: "OpenDrawingPDF",
data: { DNumber : dbNumber },
cache: false,
type: "GET"
});
}
</script>
controller:
public void OpenDrawingPDF(string DNumber)
{
string Path = #"\\serv1\Company\10 - Production\Production Drawings\CAD pdf\";
if (DNumber != null && Directory.Exists(Path))
{
string Folder = DNumber.Substring(4, 2) + #"\";
System.Diagnostics.Process.Start(Path + Folder + DNumber + ".pdf");
}
}

How to append multiple files into formdata using jquery

I am using a input type file with multiple attribute. I want to save the files into a folder. But i am not sure how to append multiple files. Help will be greatly appreciated.
Script
$(document).on('click', '.btnSubmit', function () {
var data = new FormData();
var files = $('[type="file"]').get(0).files;
if (files.length > 0) {
_.each(files, function (program, idx) {
data.append("file", program);
});
}
_appFun._ajaxcall({
type: "POST",
url: '/application/test/saveFiles',
type: 'POST',
data: data,
cache: false,
contentType: false,
processData: false,
success: function (data) {
//show content
alert('Success!')
}
});
});
C#
[HttpPost]
public ActionResult saveFiles()
{
string directory = AppSettings.Application.uploadFolder;
HttpPostedFileBase file = Request.Files["file"];
if (file != null && file.ContentLength > 0)
{
var fileName = Path.GetFileNameWithoutExtension(file.FileName);
string extension = Path.GetExtension(file.FileName);
var randomId = uniqId();
file.SaveAs(Path.Combine(directory, fileName + randomId + extension));
}
return RedirectToAction("Index");
}
If you are trying to cycle through the same input area, you can do:
var data = new FormData();
var files = $('[type="file"]')[0].files;
if (files.length > 0) {
var count = 0;
$(files).each(function(i, value){
count++;
var variableName = "name" + count;
data.append(variableName, value[i].files[0]);
}
}

Ajax Response Doesn't work from server side (iis)

I try to save a file (image) on C# MVC and JS with the following function js
function Add() {
var data = new FormData();
var files = $("#txtUploadFile").get(0).files;
var cod = document.getElementById('cod').value;
var mat = document.getElementById('mat').value;
var status = document.getElementById('status').value;
var plant = document.getElementById('plant').value;
if (files.length > 0) {
if (window.FormData !== undefined) {
var data = new FormData();
for (var x = 0; x < files.length; x++) {
data.append("file" + x, files[x]);
data.append("mat", mat);
data.append("status", status);
data.append("plant", plant);
data.append("code", cod);
}
$.ajax({
type: 'POST',
url: '/Pred/Admin/AddPred',
contentType: false,
processData: false,
data: data,
success: function (response) {
if(response.msg == 1)
{
refreshTable(response.data);
}
alert('Predio agregado.');
},
error: function (xhr, status, p3, p4) {
var err = "Error " + " " + status + " " + p3 + " " + p4;
if (xhr.responseText && xhr.responseText[0] == "{")
err = JSON.parse(xhr.responseText).Message;
}
});
}
}
}
and on the codebehind I used it
public ActionResult AddPred()
{
int isInsert=0;
string route = ConfigurationManager.AppSettings["MAPS_ROUTE"];
string[] status, plants, mats, codes;
int stat;
try
{
var requeststatus = Request.Params;
status = requeststatus.GetValues("status");
plants = requeststatus.GetValues("plant");
codes = requeststatus.GetValues("cod");
mats = requeststatus.GetValues("mat");
if (status[0] == "On")
stat= 1;
else
stat= 0;
string plant = plants[0];
string mat = mats[0];
string code = codes[0];
foreach (string file in Request.Files)
{
var fileContent = Request.Files[file];
if (fileContent != null && fileContent.ContentLength > 0)
{
var fileName = fileContent.FileName;
var path = Path.Combine(Server.MapPath(route), fileName);
path = Server.MapPath(route) + fileName;
var sqlpath = "." + route + "/" + fileName;
fileContent.SaveAs(path);
isInsert = ma.InsertPred(code, mat, stat, plant, sqlpath);
}
}
merge.preds = ma.GetPreds();
return Json(new { success = true, data = merge.preds, msg = isInsert }, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
Response.StatusCode = (int)HttpStatusCode.BadRequest;
return Json("add failed");
}
}
But the server response ever is
POST myserver/Preds/Admin/AddPred 500 (Internal Server Error)
and I used console.log but I can't to get the error information, When used this code on local side, it's runs Okey, save the image and return model for refresh the front, but when put the aplication on the server, only return error, others funtions works (modal show, return model with json) but doesn't work save a image, I set permissions (write, load, modify) on the server folder,
someone give a idea for solves this problem, I don't know whats wrong
Try like this :
function getCities(id) {
$.ajax({
type: "POST",
url: "#Url.Action("Index", "Default")",
data: '{id: id }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
//alert(response.responseData);
window.location = '/Default/YourView';//
},
error: function (response) {
alert("error!"); //
}
});
}
//In your controller
public JsonResult Index(string id)
{
merge.country= mp.Country();
merge.city= mp.City(id);
return Json("you can return an object or a string, what you want");
}

Activate button is not working in jQuery html table while bind in JSON C#

Error provide that input string was not in correct format in this line:
objproject.CategoryStatus(Convert.ToInt32(Id), true);
This is my aspx code:
[WebMethod]
public static void ActivateSelected(String Id)
{
clsCategoryBL objproject = new clsCategoryBL();
string[] arr = Id.Split(',');
foreach (var id in arr)
{
if (!string.IsNullOrEmpty(id))
{
objproject.CategoryStatus(Convert.ToInt32(Id), true);
}
}
}
This is my jQuery bind code:
function ActivateSelected()
{
var ids = '';
var cells = Array.prototype.slice.call(document.getElementById("example1").getElementsByTagName('td'));
debugger;
for (var i in cells) {
var inputArray = cells[i].getElementsByTagName('input');
for (var i = 0; i < inputArray.length; i++) {
if (inputArray[i].type == 'checkbox' && inputArray[i].checked == true) {
debugger;
ids += inputArray[i].id + ',';
}
}
}
debugger;
var urldata = "WebForm5.aspx/ActivateSelected";
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: "true",
cache: "false",
url: urldata,
data: "{Id:'" + ids + "'}",
success: function (dt)
{
debugger;
debugger;
$("#example1").DataTable();
//$("#example1").bind;
debugger;
},
error: function (result) {
alert("Error");
//console.log();
//alert(result);
}
});
}
This is my BL Class:
public string CategoryStatus(int CategoryID, bool Status)
{
using (KSoftEntities db = new KSoftEntities())
{
try
{
var ProjectDetails = db.tblCategories.Where(i => i.CategoryID == CategoryID).ToList();
ProjectDetails[0].Status = Status;
db.SaveChanges();
if (Status == true)
return "Record Activated successfully";
else
return "Record deactivated successfully";
}
catch (Exception ex)
{
}
return "Error on updation";
}
}
The Last ID is attached with extra comma,
Like : "1234,123,12345,"
spliting string of above example will create array of 4 elements, having empty string in last element. Thats why its Throwing error.
You need to handle the ids += inputArray[i].id + ','; in jquery.
here you can check whether the id is last id in the list and does that require comma after that.
function ActivateSelected()
{
var ids = '';
var cells = Array.prototype.slice.call(document.getElementById("example1").getElementsByTagName('td'));
debugger;
for (var i in cells) {
var inputArray = cells[i].getElementsByTagName('input');
for (var i = 0; i < inputArray.length; i++) {
if (inputArray[i].type == 'checkbox' && inputArray[i].checked == true) {
debugger;
ids += inputArray[i].id + ',';
}
}
}
ids = ids.substring(0,ids.lastIndexOf(','));
debugger;
var urldata = "WebForm5.aspx/ActivateSelected";
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: "true",
cache: "false",
url: urldata,
data: "{Id:'" + ids + "'}",
success: function (dt)
{
debugger;
debugger;
$("#example1").DataTable();
//$("#example1").bind;
debugger;
},
error: function (result) {
alert("Error");
//console.log();
//alert(result);
}
});
}

how to fetch return values between jquery functions and post ajax jquery request to webservice

I have the following code where the function codeaddress geocodes the text feild value and returns geocoded value , geocoded value is stored in variable example ,how will i return the variable v2 to the function call and post to asmx webservice.
<script type="text/javascript">
$(document).ready(function() {
$('#SubmitForm').submit(function() {
var geocoder;
var map;
function codeAddress(state) {
var address = document.getElementById("state").value;
geocoder.geocode( { 'address': state}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var v2=results[0].geometry.location;
alert(example);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
return v2;
});
var businessname = ($("#businessname").val());
var keyword = ($("#keyword").val());
var description = ($("#textarea").val());
var zipcode = ($("#zipcode").val());
var streetno = ($("#streetno").val());
var streetname = ($("#streetname").val());
var state = $('#state :selected').text();
var telephone = ($("#telephone").val());
var email = ($("#email").val());
var username = ($("#username").val());
var password = ($("#pass").val());
var repassword = ($("#pass1").val());
//data: "{'businessname':" + businessname + "'keyword':" + keyword + "}",
alert(state);
var v2=codeAddress(state);
alert(example);
var jsonobject = "{\"businessname\":\"" + businessname + "\",\"keyword\":\"" + keyword + "\",\"description\":\"" + description + "\",\"zipcode\":\"" + zipcode + "\",\"streetno\":\"" + streetno + "\",\"streetname\":\"" + streetname + "\",\"state\":\"" + state + "\",\"telephone\":\"" + telephone + "\",\"email\":\"" + email + "\",\"username\":\"" + username + "\",\"password\":\"" + password + "\",\"repassword\":\"" + repassword + "\"}";
$.ajax({
type: "POST",
url: "/BlockSeek/jsonwebservice.asmx/SubmitList",
data: jsonobject,
contentType: "application/json; charset=utf-8",
success: ajaxCallSucceed,
dataType: "json",
failure: ajaxCallFailed
});
});
function ajaxCallFailed(error) {
alert("error");
}
function ajaxCallSucceed(response) {
if (response.d == true) {
alert(" sucessfully saved to database");
}
else {
alert("not saved to database");
}
}
});
</script>
You call the codeAddress method with a callback. Inside codeAddress when you get value of v2, call the callback function passing it v2.
codeAddress(state,
function(v2) {
var jsonobject = "{\"businessname\":\"" + businessname/*.. use v2 in buiding jsonobject..*/;
$.ajax({
type: "POST",
url: "/BlockSeek/jsonwebservice.asmx/SubmitList",
data: jsonobject,
contentType: "application/json; charset=utf-8",
success: ajaxCallSucceed,
dataType: "json",
failure: ajaxCallFailed
});
}
);
function codeAddress(state, callback) {
var address = document.getElementById("state").value;
geocoder.geocode(...);
// ...
var v2=results[0].geometry.location;
callback(v2);
}

Categories

Resources