Excel file reading in mvc5 using javascript function - jquery-file-upload

The Excel sheet want to read while it upload on a button click in MVC5.The uploaded excel file name is passed into action using AJAX method.Here the file variable get null value in posted method.
Here how can pass selected file as HttpPostedFileBase in the below ajax method.
`
<input style="display:none" type="file" id="fileupload1" />
<button type="button" onclick='$("#fileupload1").click()'>UPLOAD FROM EXCEL</button>
<span style="display:none" id="spnName"></span>
$(function () {$("#fileupload1").change(function () {
$("#spnName").html($("#fileupload1").val().substring($("#fileupload1").val().lastIndexOf('\\') + 1));
var file = $("#spnName").html();
$.ajax({
url: "UploadExcelForContractStaff",
type: 'POST',
data: JSON.stringify({ file: file }),
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function (data) {
}
});
});
});`
[AcceptVerbs(HttpVerbs.Post)]
public string UploadExcelForContractStaff(HttpPostedFileBase uploadFile)
{
StringBuilder strValidations = new StringBuilder(string.Empty);
try
{
if (uploadFile.ContentLength > 0)
{
string filePath = Path.Combine(HttpContext.Server.MapPath("../Uploads"),
Path.GetFileName(uploadFile.FileName));
uploadFile.SaveAs(filePath);
DataSet ds = new DataSet();
//A 32-bit provider which enables the use of
string ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath + ";Extended Properties=Excel 12.0;";
using (OleDbConnection conn = new System.Data.OleDb.OleDbConnection(ConnectionString))
{
conn.Open();
using (DataTable dtExcelSchema = conn.GetSchema("Tables"))
{
string sheetName = dtExcelSchema.Rows[0]["TABLE_NAME"].ToString();
string query = "SELECT * FROM [" + sheetName + "]";
OleDbDataAdapter adapter = new OleDbDataAdapter(query, conn);
//DataSet ds = new DataSet();
adapter.Fill(ds, "Items");
if (ds.Tables.Count > 0)
{
if (ds.Tables[0].Rows.Count > 0)
{
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
//Now we can insert this data to database...
}
}
}
}
}
}
}
catch (Exception ex) { }
return "";
}

I got solution. changed code like
<form enctype="multipart/form-data" id="frmUplaodFileAdd">
#Html.AntiForgeryToken()
<input style="display:none" type="file" id="fileupload1" />
<button type="button" onclick='$("#fileupload1").click()'>UPLOAD FROM EXCEL</button>
<span style="display:none" id="spnName"></span>
</form>
$.ajax({
url: "UploadFile", //Server script to process data
type: 'POST',
async: false,
xhr: function () { // Custom XMLHttpRequest
var myXhr = $.ajaxSettings.xhr();
if (myXhr.upload) { // Check if upload property exists
myXhr.upload.addEventListener('progress',
progressHandlingFunction, false); // For handling the progress of the upload
}
return myXhr;
},
data: formData,
//Options to tell jQuery not to process data or worry about content-type.
cache: false,
contentType: false,
processData: false,
success: function (data) { }
});
[HttpPost]
public ActionResult UploadFile(HttpPostedFileBase file)
{return Json();
}

Related

Sending files from angular 6 application to spring boot web api "Required request part 'file' is not present"

I'm trying to send an file from angular 6 front-end to spring boot web API.
but it gives me following error
Bad Request","message":"Required request part 'file' is not present
here is my html code to upload file
<div class="form-group">
<label for="exampleInputFile">File input</label>
<input type="file" name="file" (change)="fileChange($event)" class="form-control-file" id="exampleInputFile" aria-describedby="fileHelp">
</div>
<button (click)="uploadFile()" type="button" class="btn btn-primary">Upload</button>
here is my ts code
formData:FormData = new FormData();
readytoupload:boolean=false;
fileChange(event) {
let fileList: FileList = event.target.files;
if(fileList.length > 0) {
let file: File = fileList[0];
this.formData.append('file', file);
this.readytoupload =true;
}
}
uploadFile(){
if(this.readytoupload){
this.featureservice.uploadFIle(this.formData).subscribe(data => {
const a = data.json();
this.goToProcess(a.process_id)
});
}
}
Here is the angular serivice
uploadFIle(formData:FormData){
let headers = new Headers();
headers.append('Accept', 'application/json');
headers.append("Content-Type", 'multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW');
return this.http.post(this.url+'upload',formData,{headers: headers})
};
this is the back-end controller
#CrossOrigin(origins = "*")
#PostMapping(value = "api/upload")
public String uploadReviews(#RequestParam("file") MultipartFile file, RedirectAttributes redirectAttributes) {
if (file.isEmpty()) {
return null;
}
try {
byte[] bytes = file.getBytes();
Path path = Paths.get(uploadFolder + file.getOriginalFilename());
uploadFile = path.toString();
Files.write(path, bytes);
sessionID = "6";
} catch (IOException e) {
e.printStackTrace();
return null;
return sessionID;
}
above API service is perfectly working with Postman requests. But not working with angular requests.
Can any one please help me on this?
Instead of this :-
return this.http.post(this.url+'upload',formData,{headers: headers})
Use this :-
return this.http.post(this.url+'upload',{"file" : formData},{headers: headers})
Hope this helps
this worked for me
downloadPdf(file: File): Observable<HttpEvent<any>>{
const formData: FormData = new FormData();
formData.append('file', file);
const req = new HttpRequest('POST', `${this.url}/upload`, formData, {
reportProgress: true,
responseType: 'arraybuffer' as 'json'
});
return this.http.request(req);
}

upload base64 image facebook graph api how to use this script

Upload Base64 Image Facebook Graph API
i want to use this script that link is attached how i can use this in my wordpress post?
i want to use this for fbcover photo site.
Take a look at this code I hacked together from various examples - you can use this to post a pure base64 string to the Facebook API - no server side processing.
Here's a demo: http://rocky-plains-2911.herokuapp.com/
This javascript handles the converting of a HTML5 Canvas element to base64 and using the Facebook API to post the image string
<script type = "text/javascript">
// Post a BASE64 Encoded PNG Image to facebook
function PostImageToFacebook(authToken) {
var canvas = document.getElementById("c");
var imageData = canvas.toDataURL("image/png");
try {
blob = dataURItoBlob(imageData);
} catch (e) {
console.log(e);
}
var fd = new FormData();
fd.append("access_token", authToken);
fd.append("source", blob);
fd.append("message", "Photo Text");
try {
$.ajax({
url: "https://graph.facebook.com/me/photos?access_token=" + authToken,
type: "POST",
data: fd,
processData: false,
contentType: false,
cache: false,
success: function (data) {
console.log("success " + data);
$("#poster").html("Posted Canvas Successfully");
},
error: function (shr, status, data) {
console.log("error " + data + " Status " + shr.status);
},
complete: function () {
console.log("Posted to facebook");
}
});
} catch (e) {
console.log(e);
}
}
// Convert a data URI to blob
function dataURItoBlob(dataURI) {
var byteString = atob(dataURI.split(',')[1]);
var ab = new ArrayBuffer(byteString.length);
var ia = new Uint8Array(ab);
for (var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
return new Blob([ab], {
type: 'image/png'
});
}
</script>
This handles the Facebook Authentication and shows basic HTML setup
<script type="text/javascript">
$(document).ready(function () {
$.ajaxSetup({
cache: true
});
$.getScript('//connect.facebook.net/en_UK/all.js', function () {
// Load the APP / SDK
FB.init({
appId: '288585397909199', // App ID from the App Dashboard
cookie: true, // set sessions cookies to allow your server to access the session?
xfbml: true, // parse XFBML tags on this page?
frictionlessRequests: true,
oauth: true
});
FB.login(function (response) {
if (response.authResponse) {
window.authToken = response.authResponse.accessToken;
} else {
}
}, {
scope: 'publish_actions,publish_stream'
});
});
// Populate the canvas
var c = document.getElementById("c");
var ctx = c.getContext("2d");
ctx.font = "20px Georgia";
ctx.fillText("This will be posted to Facebook as an image", 10, 50);
});
</script>
<div id="fb-root"></div>
<canvas id="c" width="500" height="500"></canvas>
<a id="poster" href="#" onclick="PostImageToFacebook(window.authToken)">Post Canvas Image To Facebook</a>
I needed this too, and was not happy with all the code around it because it is lengthy and usually needs jQuery. Here is my code for uploading from Canvas to Facebook:
const dataURItoBlob = (dataURI) => {
let byteString = atob(dataURI.split(',')[1]);
let ab = new ArrayBuffer(byteString.length);
let ia = new Uint8Array(ab);
for (let i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
return new Blob([ia], {
type: 'image/jpeg'
});
}
const upload = async (response) => {
let canvas = document.getElementById('canvas');
let dataURL = canvas.toDataURL('image/jpeg', 1.0);
let blob = dataURItoBlob(dataURL);
let formData = new FormData();
formData.append('access_token', response.authResponse.accessToken);
formData.append('source', blob);
let responseFB = await fetch(`https://graph.facebook.com/me/photos`, {
body: formData,
method: 'post'
});
responseFB = await responseFB.json();
console.log(responseFB);
};
document.getElementById('upload').addEventListener('click', () => {
FB.login((response) => {
//TODO check if user is logged in and authorized publish_actions
upload(response);
}, {scope: 'publish_actions'})
})
Source: http://www.devils-heaven.com/facebook-javascript-sdk-photo-upload-from-canvas/

multipart form save as attributes in backbonejs

Can any body give example to save the multipart form by using backbone js model?
How to combine the form data with file data and save to model
I am setting the model attributes and how to include the file data in the attributes. I adapted the code from one of the site to Forc Backbone to save an attribute as a file. I could not relate it to my form
<form enctype="multipart/form-data">
<input type="file" name="ImageData">
<input type="text" name="UserName">
</form>
Model
User = Backbone.Model.extend({
readAvatar : function (file, callback) {
var reader = new FileReader(); // File API object for reading a file locally
reader.onload = (function (theFile, self) {
return function (e) {
// Set the file data correctly on the Backbone model
self.set({avatar_file_name : theFile.name, avatar_data : fileEvent.target.result});
// Handle anything else you want to do after parsing the file and setting up the model.
callback();
};
})(file, this);
reader.readAsDataURL(file); // Reads file into memory Base64 encoded
}
attribute : function(attr) {
return Object.defineProperty(this.prototype, attr, {
get: function() {
return this.get(attr);
},
set: function(value) {
var attrs;
attrs = {};
attrs[attr] = value;
return this.set(attrs);
}
});
};
});
var form_data = form.serializeArray();
View
this.model.data = form_data;
var profiledata;
if (window.FormData) {
profiledata = new FormData();
console.log(profiledata);
}
if (profiledata) {
jQuery.each($('#ImageData')[0].files, function(i, file) {
//reader.readAsDataURL(file);
profiledata.append("ImageData[]", file);
});
}
this.model.ImageData = profiledata;
//and save the data
this.model.save
Rather than handling the FileReader logic in the model, I've been managing that in the view.
Check this out:
<form enctype="multipart/form-data">
<input type="file" name="ImageData">
<input type="text" name="UserName">
<button>Submit</button>
</form>
View:
var FormView = Backbone.View.extend({
events: {
"submit form" : "submit",
"change input[type=file]" : "encodeFile"
},
render: function () {
var content = this.template();
this.$el.html(content);
return this;
},
encodeFile: function (event) {
var file = event.currentTarget.files[0];
var reader = new FileReader();
reader.onload = function (fileEvent) {
this.model.set({
avatar_data: fileEvent.target.result // file name is part of the data
});
}.bind(this)
reader.onerror = function () {
console.log("error", arguments)
}
reader.readAsDataURL(file);
},
submit: function (event) {
event.preventDefault();
this.model.set({ UserName: $('input[name=UserName]').val() });
this.model.save();
}
});

How to upload multiple files on separate Forms by Ajax upload?

I've worked on this but couldn't fully figure out.
Basically, what I need is to upload 2 or more files separately (only on demand one by one, not all files at once) using Ajax upload. Currently, I have 2 file inputs but somehow, the JavaScript code always uploads the first file input (the one inside "formContentProperty").
Here is my HTML code:
<div>
<form enctype="multipart/form-data" id="formContentProperty">
<input id="fileContentProperty" type="file" name="fileContentProperty" />
<a id="uploadbuttonContentProperty" href="javascript:void(0)">
<span>Upload 1</span>
</a>
</form>
<progress></progress>
</div>
<div>
<form enctype="multipart/form-data" id="formContentPreviewImage">
<input id="fileContentPreviewImage" type="file" name="fileContentPreviewImage"/>
<a id="uploadbuttonContentPreviewImage" href="javascript:void(0)">
<span>Upload 2</span>
</a>
</form>
<progress></progress>
</div>
Here is my JavaScript code:
$('#uploadbuttonContentProperty').click(function () {
return UpdoadFile('formContentProperty', 'divUploadContentPropertyResultMessage');
});
$('#uploadbuttonContentPreviewImage').click(function () {
return UpdoadFile('formContentPreviewImage', 'divUploadContentPreviewImageResultMessage');
});
function UpdoadFile(formElementId, divMessageElementId) {
var formData = new FormData($('form')[0]);
$.ajax({
url : '<%= base.AjaxUploadHandlerPath %>', //Server script to process data
type : 'POST',
xhr : function() { // Custom XMLHttpRequest
var myXhr = $.ajaxSettings.xhr();
if(myXhr.upload){ // Check if upload property exists
myXhr.upload.addEventListener('progress',progressHandlingFunction, false); // For handling the progress of the upload
}
return myXhr;
},
//beforeSend: beforeSendHandler,
success : function(response) {
var obj = $.parseJSON(response);
$('#' + divMessageElementId).html(obj.ResultMessage);
},
//error : errorHandler,
data : formData,
//Options to tell jQuery not to process data or worry about content-type.
cache : false,
contentType : false,
processData : false
});
};
function progressHandlingFunction(e){
if(e.lengthComputable)
$('progressContentProperty').attr({ value: e.loaded, max: e.total });
}
I'd really appreciate any help.
To upload files using ajax file upload
<script>
function uploadFiles()
{
var files = $('#previewFile')[0].files;
var totalFiles = files.length
for(var i=0; i < totalFiles; i++)
{
var formData = new FormData();
formData.append("previewFile",files[i]);
doAjaxFileUpload("/storeTempFile.do", formData,function(data)
{
data = eval(data);
if (data.result=="success")
{
alert("File uploaded successfully");
}
else
{
alert("Error occured : "+data);
}
},
function(data)
{
alert("Error occured : "+data);
});
}
}
function doAjaxFileUpload(actionURL,params,callbackSuccessFunction,callbackFailureFunction)
{
$.ajax(
{
url: actionURL,
type: "POST",
data: params,
processData: false,
contentType: false,
error: callbackFailureFunction,
success : callbackSuccessFunction
});
}
</script>

How can i make an image as an Ajax Action Link?

How can i make an image as an Ajax Action Link?
You could do this:
<a href="<%: Url.Action("someaction", "somecontroller") %>" id="mylink">
<img src="<%: Url.Content("~/images/foo.png") %>" alt="foo" />
</a>
and then in a separate javascript file AJAXify this link:
$(function() {
$('#mylink').click(function() {
$.ajax({
url: this.href,
type: 'GET',
success: function(result) {
alert('success');
}
});
return false;
});
});
And if you want to avoid the tag soup in your views you could write a custom helper:
public static class HtmlExtensions
{
public static MvcHtmlString ImageLink(this HtmlHelper htmlHelper, string actionName, string controllerName, object routeValues, object htmlAttributes, string imageSource)
{
var urlHelper = new UrlHelper(htmlHelper.ViewContext.RequestContext, htmlHelper.RouteCollection);
var image = new TagBuilder("img");
image.Attributes["src"] = urlHelper.Content(imageSource);
var anchor = new TagBuilder("a");
anchor.Attributes["href"] = urlHelper.Action(actionName, controllerName, routeValues);
anchor.MergeAttributes(new RouteValueDictionary(htmlAttributes));
anchor.InnerHtml = image.ToString(TagRenderMode.SelfClosing);
return MvcHtmlString.Create(anchor.ToString());
}
}
and then in your view simply:
<%: Html.ImageLink(
"someaction",
"somecontroller",
null,
new { id = "mylink" },
"~/images/foo.png"
) %>
and of course the process of AJAXifying it stays the same.
What about something like:
<a href='<%= Url.Action(...) %>'><img src='...' /></a>
Not certain if there is a helper that does this.
Bob
To push the id to the edit control whilst displaying an edit image instead of the word Spag you can try this:
#MvcHtmlString.Create(
Ajax.ActionLink("Spag", "Edit",
new { id = item.x0101EmployeeID },
new AjaxOptions() {
UpdateTargetId = "selectDiv",
InsertionMode = InsertionMode.Replace,
HttpMethod = "GET"
}
).ToHtmlString().Replace(
"Spag",
"<img src=\"" + Url.Content("../../Images/edit.png") + "\" />"
)
)