Upload file failed to save in Database - javascript
public JsonResult SaveAttachment(string buyerCode)
{
Dictionary<int, CheckSessionData> IDictionary = CheckSessionData.GetSessionValues();
long companyId = (long)IDictionary[1].Id;
long userId = (long)IDictionary[3].Id;
var buyer = DB.Buyers.FirstOrDefault(x => x.Code == buyerCode);
string basePath = "~/Upload/BuyerAttachment/";
string path = Server.MapPath(basePath);
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
HttpFileCollectionBase files = Request.Files;
List<string> filePathList = new List<string>();
for (int i = 0; i > files.Count; i++)
{
HttpPostedFileBase file = files[i];
var date = DateTime.Now.ToString().Replace('/', '_');
string FilePath = Path.Combine(path, date.Replace(':', ' ') + file.FileName);
file.SaveAs(FilePath);
filePathList.Add(FilePath);
}
foreach (var item in filePathList)
{
var buyerAttachment = new Buyer_Attachment();
buyerAttachment.BuyerId = buyer.BuyerId;
buyerAttachment.DateOfEntry = DateTime.Now;
buyerAttachment.EntryBy = userId;
buyerAttachment.AttachmentURL = path;
DB.Buyer_Attachment.Add(buyerAttachment);
}
try
{
DB.SaveChanges();
}
catch (Exception)
{
return Json(false, JsonRequestBehavior.AllowGet);
}
return Json(true);
}
}
function SaveAttachment(code) {
var files = $("#CustomerAttachment").get(0).files;
var fileData = new FormData();
for (var i = 0; i < files.length; i++) {
fileData.append("fileInput", files[i]);
}
$.ajax({
type: "POST",
url: "/BuyerSimple/SaveAttachment?buyerCode="+code,
dataType: "json",
contentType: false, // Not to set any content header
processData: false, // Not to process data
data: fileData,
success: function (result, status, xhr) {
filePathList = result;
$('#AttachmentPathList').val(result);
},
error: function (xhr, status, error) {
alert(status);
}
});
}
Related
Javascript Fetch does not provide my content in Response message
I am struggling with the Response of the Javascript fetch() method. What is my objective: a) to send multiple lines to the backend to save those to a database and b) get a guid in return for further processing. I succeed in objective a (save to database), but the return message fails to materialise. Response.ok is true, but no message is part of the return message. What should I do to accomplish this? My javascript is: function saveAll(event) { event.preventDefault(); var newDeelnemers = new Array(); var lijst = document.querySelectorAll('#tblDeelnemers tbody tr') lijst.forEach(function (dnmr) { var row = dnmr; var deelnemer = {}; var nDnmr = row.children; //deelnemer.Id = nDnmr[0].innerHTML; deelnemer.FamilielidFirstName = nDnmr[0].innerHTML; deelnemer.Achternaam = nDnmr[1].innerHTML; deelnemer.DOB = nDnmr[2].innerHTML; deelnemer.Programma = nDnmr[3].innerHTML; deelnemer.EetMee = nDnmr[4].firstChild.checked; deelnemer.Dieet = nDnmr[5].innerHTML; deelnemer.Bedrag = nDnmr[6].innerHTML; newDeelnemers.push(deelnemer); }); fetch("/Familiedag/Registreer", { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(newDeelnemers) }).then(function (response) { console.log('eerste keer: ' + response); if (response.ok) { alert('De registratie is gelukt'); //redirect("/Familiedag/RegistreerConfirm?") } }); } The controller [HttpPost] public IActionResult Registreer([FromBody] List<FdDeelnemer> newDeelnemers) { if (newDeelnemers.Count == 0) { return null; } Guid registratieGuid = Guid.NewGuid(); foreach (var ndn in newDeelnemers) { FdDeelnemer VM = new FdDeelnemer(); VM.RegistratieGuid = registratieGuid; VM.FamilielidFirstName = ndn.FamilielidFirstName; VM.Achternaam = ndn.Achternaam; VM.EetMee = ndn.EetMee; VM.Dieet = ndn.Dieet; VM.Programma = ndn.Programma; VM.DOB = ndn.DOB; VM.Bedrag = ndn.Bedrag; VM.CreatedBy = User.Identity.Name; VM.CreatedOn = DateTime.UtcNow; _context.Add(VM); } Guid geregistreerdeDeelnemers = registratieGuid; return Json(geregistreerdeDeelnemers); }
add another .then that return the json fetch("/echo/json/", { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ "tes": "data" }) }).then(function(response) { return response.json(); }).then(function(json) { console.log('eerste keer: ', json); alert('De registratie is gelukt'); //redirect("/Familiedag/RegistreerConfirm?") });
You can try to return it like that: return Json(new { AnythingYouWant = geregistreerdeDeelnemers });
How can i filter out undefined from string
Hello Im fetching some data from an api and returning the response als text. Then im passing the result to another function where i want to format that data to get an JSON Object. But i always get undefined when i want to trim the data. When i do indexOf(undefined) it returns index -1. Here is an example of the data: ,result,table,_start,_stop,_time,_value,Wizard,_field,_measurement,botName,errorLevel,errorLeveldescription,pcName,status,stepNr ,mean,0,2021-03-19T19:33:44.870040506Z,2021-04-18T19:33:44.870040506Z,2021-04-15T07:02:30Z,1,IPA_BOT,value,ipaMeasurement,IPA_BOT_1,400,INFO,SCHWCL07347,OK,1 ,mean,0,2021-03-19T19:33:44.870040506Z,2021-04-18T19:33:44.870040506Z,2021-04-15T07:03:40Z,1,IPA_BOT,value,ipaMeasurement,IPA_BOT_1,400,INFO,SCHWCL07347,OK,1 ,mean,0,2021-03-19T19:33:44.870040506Z,2021-04-18T19:33:44.870040506Z,2021-04-15T08:27:00Z,1,IPA_BOT,value,ipaMeasurement,IPA_BOT_1,400,INFO,SCHWCL07347,OK,1 ,mean,0,2021-03-19T19:33:44.870040506Z,2021-04-18T19:33:44.870040506Z,2021-04-15T08:28:30Z,1,IPA_BOT,value,ipaMeasurement,IPA_BOT_1,400,INFO,SCHWCL07347,OK,1 ,mean,0,2021-03-19T19:33:44.870040506Z,2021-04-18T19:33:44.870040506Z,2021-04-15T08:28:45Z,1,IPA_BOT,value,ipaMeasurement,IPA_BOT_1,400,INFO,SCHWCL07347,OK,1 ,mean,0,2021-03-19T19:33:44.870040506Z,2021-04-18T19:33:44.870040506Z,2021-04-15T08:29:20Z,2,IPA_BOT,value,ipaMeasurement,IPA_BOT_1,400,INFO,SCHWCL07347,OK,1 ,mean,0,2021-03-19T19:33:44.870040506Z,2021-04-18T19:33:44.870040506Z,2021-04-15T08:35:40Z,2,IPA_BOT,value,ipaMeasurement,IPA_BOT_1,400,INFO,SCHWCL07347,OK,1 ,mean,0,2021-03-19T19:33:44.870040506Z,2021-04-18T19:33:44.870040506Z,2021-04-15T09:43:40Z,4,IPA_BOT,value,ipaMeasurement,IPA_BOT_1,400,INFO,SCHWCL07347,OK,1 ,mean,0,2021-03-19T19:33:44.870040506Z,2021-04-18T19:33:44.870040506Z,2021-04-15T09:45:05Z,5,IPA_BOT,value,ipaMeasurement,IPA_BOT_1,400,INFO,SCHWCL07347,OK,1 ,mean,0,2021-03-19T19:33:44.870040506Z,2021-04-18T19:33:44.870040506Z,2021-04-15T09:51:10Z,5,IPA_BOT,value,ipaMeasurement,IPA_BOT_1,400,INFO,SCHWCL07347,OK,1 ,mean,1,2021-03-19T19:33:44.870040506Z,2021-04-18T19:33:44.870040506Z,2021-04-15T08:35:45Z,2,IPA_BOT,value,ipaMeasurement,IPA_BOT_1,400,INFO,SCHWCL07347,OK,2 ,mean,1,2021-03-19T19:33:44.870040506Z,2021-04-18T19:33:44.870040506Z,2021-04-15T09:43:45Z,4,IPA_BOT,value,ipaMeasurement,IPA_BOT_1,400,INFO,SCHWCL07347,OK,2 ,mean,1,2021-03-19T19:33:44.870040506Z,2021-04-18T19:33:44.870040506Z,2021-04-15T09:45:10Z,5,IPA_BOT,value,ipaMeasurement,IPA_BOT_1,400,INFO,SCHWCL07347,OK,2 ,mean,1,2021-03-19T19:33:44.870040506Z,2021-04-18T19:33:44.870040506Z,2021-04-15T09:51:10Z,5,IPA_BOT,value,ipaMeasurement,IPA_BOT_1,400,INFO,SCHWCL07347,OK,2 ,mean,2,2021-03-19T19:33:44.870040506Z,2021-04-18T19:33:44.870040506Z,2021-04-15T08:35:50Z,2,IPA_BOT,value,ipaMeasurement,IPA_BOT_1,400,INFO,SCHWCL07347,OK,3 ,mean,2,2021-03-19T19:33:44.870040506Z,2021-04-18T19:33:44.870040506Z,2021-04-15T09:43:45Z,4,IPA_BOT,value,ipaMeasurement,IPA_BOT_1,400,INFO,SCHWCL07347,OK,3 ,mean,2,2021-03-19T19:33:44.870040506Z,2021-04-18T19:33:44.870040506Z,2021-04-15T09:45:10Z,5,IPA_BOT,value,ipaMeasurement,IPA_BOT_1,400,INFO,SCHWCL07347,OK,3 ,mean,2,2021-03-19T19:33:44.870040506Z,2021-04-18T19:33:44.870040506Z,2021-04-15T09:51:15Z,5,IPA_BOT,value,ipaMeasurement,IPA_BOT_1,400,INFO,SCHWCL07347,OK,3 ,mean,3,2021-03-19T19:33:44.870040506Z,2021-04-18T19:33:44.870040506Z,2021-04-15T08:35:55Z,2,IPA_BOT,value,ipaMeasurement,IPA_BOT_1,400,INFO,SCHWCL07347,OK,4 ,mean,3,2021-03-19T19:33:44.870040506Z,2021-04-18T19:33:44.870040506Z,2021-04-15T09:43:50Z,4,IPA_BOT,value,ipaMeasurement,IPA_BOT_1,400,INFO,SCHWCL07347,OK,4 ,mean,3,2021-03-19T19:33:44.870040506Z,2021-04-18T19:33:44.870040506Z,2021-04-15T09:45:15Z,5,IPA_BOT,value,ipaMeasurement,IPA_BOT_1,400,INFO,SCHWCL07347,OK,4 ,mean,3,2021-03-19T19:33:44.870040506Z,2021-04-18T19:33:44.870040506Z,2021-04-15T09:51:15Z,5,IPA_BOT,value,ipaMeasurement,IPA_BOT_1,400,INFO,SCHWCL07347,OK,4 ,mean,4,2021-03-19T19:33:44.870040506Z,2021-04-18T19:33:44.870040506Z,2021-04-15T08:36:00Z,2,IPA_BOT,value,ipaMeasurement,IPA_BOT_1,400,INFO,SCHWCL07347,OK,5 ,mean,4,2021-03-19T19:33:44.870040506Z,2021-04-18T19:33:44.870040506Z,2021-04-15T09:43:50Z,4,IPA_BOT,value,ipaMeasurement,IPA_BOT_1,400,INFO,SCHWCL07347,OK,5 ,mean,4,2021-03-19T19:33:44.870040506Z,2021-04-18T19:33:44.870040506Z,2021-04-15T09:45:15Z,5,IPA_BOT,value,ipaMeasurement,IPA_BOT_1,400,INFO,SCHWCL07347,OK,5 ,mean,4,2021-03-19T19:33:44.870040506Z,2021-04-18T19:33:44.870040506Z,2021-04-15T09:51:20Z,5,IPA_BOT,value,ipaMeasurement,IPA_BOT_1,400,INFO,SCHWCL07347,OK,5 ,mean,5,2021-03-19T19:33:44.870040506Z,2021-04-18T19:33:44.870040506Z,2021-04-15T08:38:10Z,2,IPA_BOT,value,ipaMeasurement,RestartMachine,400,INFO,SCHWCL07347,OK,7 export function get_influx_data() { let url = "api/url"; let myHeaders = new Headers(); myHeaders.append("Content-Type", "application/vnd.flux"); myHeaders.append("Accept", "application/csv"); myHeaders.append( "Authorization", " api Token" ); let raw = 'api query body'; let requestOptions = { method: "POST", headers: myHeaders, body: raw, redirect: "follow", }; return fetch(url, requestOptions) .then(function (response) { if (response.ok) { return response.text(); } else { return Promise.reject(response) } }).then(function (result) { return result }).catch(function (error) { console.log("error: " + error) }) }; export function clean_influx_data(result) { var data = result.trim(); var lines = data.split("\n"); var result = []; var headers = lines[0].split(","); for (var i = 1; i < lines.length; i++) { if (!lines[i]) { continue; } var obj = {}; var currentline = lines[i].split(","); for (var j = 0; j < headers.length; j++) { obj[headers[j]] = currentline[j]; } result.push(obj); } var rawJsonData = JSON.stringify(result); const parsedData = JSON.parse(rawJsonData); import { get_influx_data } from './api.js' import {clean_influx_data} from './clean_data.js' var a = get_influx_data(); a.then((result) => clean_influx_data(result)) var b = clean_influx_data()
You need to use Promise.resolve(result). return fetch(url, requestOptions) .then(function (response) { if (response.ok) { return response.text(); } else { return Promise.reject(response) } }).then(function (result) { return Promise.resolve(result); }).catch(function (error) { console.log("error: " + error) }) };
Ajax Post only working when debugging in browser
I've checked every similar question on here, the solutions and more, but still can't find a solution that works for me. First: I'm absolutely new to Ajax and just got a project to fix from some developer that isn't reachable anymore, so I'm at my wits end... Basically, this is the code-snippet for the Link that is clicked, which action works perfectly fine when I debug the whole process and just "step-over" everything, but simply running it will always end it in error instead of success. var serviceURL = "http://address"; function bestellePosition(token, artikelId, userId, menge) { var authheader = 'Bearer ' + token; var url = "/WarenkorbPositions/AddMengeToCart"; var type = "POST"; $.ajax({ cache: false, type: type, url: serviceURL + url, beforeSend: function (xhr) { xhr.setRequestHeader('Authorization', authheader); }, contentType: "application/json; charset=utf-8", data: JSON.stringify({ userId: userId, artikelId: artikelId, menge: menge }), success: function (result) { if (result.result === true) { alert('it worked'); } else { alert('it didnt work'); } }, error: function (result) { alert(result.result); } }); } Additional things I tried were adding dataType: "json", , which seemingly didn't do anything. Adding a timeout: 10000 which also didn't seem to do anything. Just sending the data as data: {...} instead of using JSON.stringify which didn't work at all. EDIT: URL-Method private PostXnameEntities db = new PostXnameEntities(); private String conStr = #"Server=xxx\SQLEXPRESS,xxx;Initial Catalog=xxx;Persist Security Info=True;UID=xxx;Password=xxx;"; public Boolean AddMengeToCart(int userId, int artikelId, decimal menge) { var positionen = db.WarenkorbPosition.Include(w => w.Artikel).Include(w => w.User); var posquery = from p in positionen where p.UserId == userId && p.ArtikelId == artikelId select p; WarenkorbPosition pos = new WarenkorbPosition(); if (posquery.ToList().Count > 0) { pos = posquery.ToList().First(); if (menge == 0) { int rows = 0; SqlConnection sqlConn = new SqlConnection(conStr); string queryOrder = "DELETE FROM [PostXname].[dbo].[WarenkorbPosition] WHERE [UserId] = #UserId And [ArtikelId] = #ArtikelId"; SqlCommand cmd = new SqlCommand(queryOrder, sqlConn); cmd.Parameters.AddWithValue("#UserId", userId); cmd.Parameters.AddWithValue("#ArtikelId", artikelId); try { sqlConn.Open(); rows = cmd.ExecuteNonQuery(); } catch (Exception) { throw; } sqlConn.Close(); } else { decimal posMenge = pos.Menge.Value; decimal MengeGesamt = posMenge + menge; int rows = 0; SqlConnection sqlConn = new SqlConnection(conStr); string queryOrder = "UPDATE [PostXname].[dbo].[WarenkorbPosition] SET [Menge] = #Menge WHERE [UserId] = #UserId And [ArtikelId] = #ArtikelId"; SqlCommand cmd = new SqlCommand(queryOrder, sqlConn); cmd.Parameters.AddWithValue("#UserId", userId); cmd.Parameters.AddWithValue("#ArtikelId", artikelId); cmd.Parameters.AddWithValue("#Menge", Convert.ToDecimal(MengeGesamt)); try { sqlConn.Open(); rows = cmd.ExecuteNonQuery(); } catch (Exception) { throw; } sqlConn.Close(); } } else { int rows = 0; SqlConnection sqlConn = new SqlConnection(conStr); string queryOrder = "INSERT INTO [PostXname].[dbo].[WarenkorbPosition]([UserId],[ArtikelId],[Menge])VALUES(#UserId,#ArtikelId,#Menge)"; SqlCommand cmd = new SqlCommand(queryOrder, sqlConn); cmd.Parameters.AddWithValue("#UserId", userId); cmd.Parameters.AddWithValue("#ArtikelId", artikelId); cmd.Parameters.AddWithValue("#Menge", Convert.ToDecimal(menge)); try { sqlConn.Open(); rows = cmd.ExecuteNonQuery(); } catch (Exception) { throw; } sqlConn.Close(); } return true; }
can you check the below code and try once. can you also check the the url method u mentioned is a GET or POST type Please also tell what u got in result in error method (result.result) var serviceURL = "http://address"; function bestellePosition(token, artikelId, userId, menge) { var authheader = 'Bearer ' + token; var url = "/WarenkorbPositions/AddMengeToCart"; var type = "POST"; $.ajax({ cache: false, type: type, url: serviceURL + url, beforeSend: function (xhr) { xhr.setRequestHeader('Authorization', authheader); }, contentType: "application/json; charset=utf-8", dataType: "json", data: JSON.stringify({ userId: userId, artikelId: artikelId, menge: menge }), success: function (result) { if (result.result === true) { alert('it worked'); } else { alert('it didn\'t work'); } }, error: function (result) { alert(result.result); } }); }
Sharepoint AddIn upload .PDF via SP REST API
i have a function, which is uploading files to list item. Everything is working for .png, but when i'm trying to upload .pdf i have error net::ERR_CONNECTION_RESET Screen of error object: My code: function uploadFile(listName, itemId, fileName, file) { uploadFileSP(listName, itemId, fileName, file) .then(function (files) { //success }, function (sender, args) { alert('error: ' + args.get_message()); }); } function getFileBuffer(file) { var deferred = $.Deferred(); var reader = new FileReader(); reader.onload = function (e) { deferred.resolve(e.target.result); } reader.onerror = function (e) { deferred.reject(e.target.error); } reader.readAsArrayBuffer(file); return deferred.promise(); } function uploadFileSP(listName, id, fileName, file) { var deferred = $.Deferred(); getFileBuffer(file) .then(function (buffer) { var bytes = new Uint8Array(buffer); var content = new SP.Base64EncodedByteArray(); var binary = ''; for (var b = 0; b < bytes.length; b++) { binary += String.fromCharCode(bytes[b]); } console.log(binary); executor.executeAsync({ url: appweburl + "/_api/web/lists/getbytitle('" + listName + "')/items(" + id + ")/AttachmentFiles/add(FileName='" + file.name + "')", method: "POST", binaryStringRequestBody: true, body: binary, success: function (data) { alert('Pomyślnie dodano fakturę!'); window.location.replace("http://sharepoint-dev.ampliapps.com/FakturyBPNT-SharePoint-Hosted/Lists/Faktury/AllItems.aspx");}, error: function (err) { alert('Wystąpił błąd podczas wprowadzania faktury.'); console.log(err); }, state: "Update" }) }, function (error) { deferred.reject(error); }); return deferred.promise(); } As i said earlier, it works for .png for example.
This is what you need function uploadDocument(contents, targetPath, successHandler, failedHandler) { var fileName = getFilenameFromUrl(targetPath); var fileNameEvidence = fileName; var folderName = getPathFromUrl(targetPath); var hostWebUrl = ''; var appWebUrl = ''; hostWebUrl = decodeURIComponent(getQueryStringParameter('SPHostUrl')); appWebUrl = decodeURIComponent(getQueryStringParameter('SPAppWebUrl')); $.getScript(hostWebUrl + "/_layouts/15/SP.RequestExecutor.js", function () { console.log("into upload Api Document"); var byteArray = new Uint8Array(atob(contents).split("").map(function (c) { return c.charCodeAt(0); })); var fileData = ''; for (var i = 0; i < byteArray.byteLength; i++) { fileData += String.fromCharCode(byteArray[i]); } var reqDocExecutor = new SP.RequestExecutor(appWebUrl); var _url = ''; var contentType = "application/pdf;odata=verbose"; var dotLocation = fileName.lastIndexOf('.'); var extensionFile = fileName.substr(dotLocation); var info; _url = String.format("{0}/_api/sp.appcontextsite(#target)/web/GetFolderByServerRelativeUrl('{1}')/files" + "/add(overwrite=true, url='{2}')?#target='{3}'", appWebUrl, folderName, fileName, hostWebUrl); info = { url: _url, method: "POST", headers: { "Accept": "application/pdf; odata=verbose", "X-RequestDigest": $("#__REQUESTDIGEST").val() }, contentType: contentType, processData: false, binaryStringRequestBody: true, body: fileData, success: function (x, y, z) { successHandler(); }, error: function (x, y, z) { console.log('failed to upload document'); failedHandler(); } }; reqDocExecutor.executeAsync(info); }); }
How to name uploaded chunk using html5?
I have this code: function upload_by_chunks() { var chunk_size = 1048576; // 1MB function slice(start, end) { if (file.slice) { return file.slice(start, end); } else if (file.webkitSlice) { return file.webkitSlice(start, end); } } var i = 0; function process(start, end) { if (start < file.size) { var chunk = slice(start, end); chunk.name = file.name; var formData = new FormData(); formData.append('file', chunk); formData.append('token', token); formData.append('path', leash.cwd); $.ajax({ url: 'lib/upload.php?append=1', type: 'POST', success: function(response) { if (response.error) { alert(response.error); } process(end, end+chunk_size); }, error: function(jxhr, error, status) { alert(jxhr.statusText); }, data: formData, cache: false, contentType: false, processData: false }); } else { alert('File "' + file.name + '" uploaded.'); } } process(0, chunk_size); } I've set the name using chunk.name = file.name; but in php the filename is blob. $fname = basename($_FILES['file']['name']);
There is an optional third parameter of the method append, which allows you to set a file name for a blob. formData.append('file', chunk, file.name);