I am trying to upload a file using jquery ajax, I can see the file object, its name, its size, etc.
In console by formdata.get("files"), but the context.request.files size is always zero, it seems the server does not receive the file from client, the HttpPostedFileBase request is always null.
How to fix it?
HTML:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="UploadKpData.aspx.cs" Inherits="WebApp.Admin.UploadKpData" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<script type="text/javascript" src="./../Scripts/jquery-1.4.4.min.js"></script>
</head>
<body>
<div>
<div>
<input type="file" id="kpData"/>
<button type="submit" id="uploadKp" />
</div>
</div>
</body>
<script>
$("#uploadKp").click(function () {
var formdata = new FormData();
var files = $("#kpData").get(0).files[0];
formdata.append("files", files);
$.ajax({
url: "../../ds/UploadExcel.ashx",
type: "POST",
async: false,
contentType: false, // Not to set any content header
processData: false, // Not to process data
data: formdata,
success: function (result) {
alert(result);
},
error: function (err) {
alert(err.statusText);
}
});
})
</script>
</html>
UploadExcel.ashx:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace WebApp.ds
{
public class UploadExcel : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
HttpFileCollection file = context.Request.Files;
HttpPostedFile file1 = file[0];
string fileName = context.Server.MapPath("~/tmp/" + "test2.xlsx");
file1.SaveAs(fileName);
context.Response.ContentType = "text/plain";
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
I have checked your code and all are working for me.
Let me share some screenshots :
Handler get file:
Project structure:
HTML page:
Related
My project have following structure.
The pages is in the html file. and server request is processed on Page_load in the other aspx page.
I created a sample application to show the error.
Here is the HTML file HTMLPage1.html
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function () {
var params = 'pak=' + encodeURIComponent('</br>');
debugger;
var url = 'http://localhost:49735/WebForm1.aspx?' + params;
$.ajax({
type: 'POST',
async: false,
url: url,
success: function (data) {
alert('Hi');
}
});
});
</script>
<meta charset="utf-8" />
Here is the PageLoad function in WebForm1.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
var authorize = Request["pak"];
int i = 0;
}
But Request["pak"] is not accessible. I should need to pass pak as </br>
If you want to call web by POST
You should set the data field
like this
$(document).ready(function () {
//var params = 'pak=' + encodeURIComponent('</br>');
debugger;
var url = 'http://localhost:49735/WebForm1.aspx';
$.ajax({
type: 'POST',
async: false,
data:{
pak : encodeURIComponent('</br>')
},
url: url,
success: function (data) {
alert('Hi');
}
});
});
encodeURIComponent('</br>') will encodeURL like "%3C%2Fbr%3E"
You can try to use HttpUtility.UrlDecode() to Decode
var authorize = HttpUtility.UrlDecode(Request["pak"].toString());
You will get </br>
Im using Google charts API to load a pie chart from json file data
Here is where the chart is created (The HTML File) :
<html>
<head>
<!--Load the AJAX API-->
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.charts.load('current', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var jsonData = $.ajax({
url: "read.jsp",
dataType: "json"
});
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(jsonData);
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, {width: 400, height: 240});
}
</script>
</head>
<body>
<!--Div that will hold the pie chart-->
<div id="chart_div" ></div>aa
</body>
</html>
And here is the Read.jsp Used in url (ajax) :
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1" import="java.io.*, java.net.*"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>JSP Reading Text File</title>
</head>
<body>
<%
String fileName = "/WEB-INF/json/test.json";
InputStream ins = application.getResourceAsStream(fileName);
try
{
if(ins == null)
{
response.setStatus(response.SC_NOT_FOUND);
}
else
{
BufferedReader br = new BufferedReader((new InputStreamReader(ins)));
String data;
while((data= br.readLine())!= null)
{
out.println(data+"<br>");
}
}
}
catch(IOException e)
{
out.println(e.getMessage());
}
%>
</body>
</html>
And as a result I get this Error "Table has no columns" :
enter image description here
Anyone Know why please ? and thank you
by default, $.ajax is asynchronous,
need to wait on the done callback...
see following snippet...
function drawChart() {
$.ajax({
url: "read.jsp",
dataType: "json"
}).done(function (jsonData) {
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(jsonData);
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, {width: 400, height: 240});
});
}
EDIT
also, remove all the html from the jsp file,
this should be all you need...
<%# page language="java" contentType="application/json; charset=UTF-8"
pageEncoding="UTF-8" import="java.io.*, java.net.*"%>
<%
String fileName = "/WEB-INF/json/test.json";
InputStream ins = application.getResourceAsStream(fileName);
try
{
if(ins == null)
{
response.setStatus(response.SC_NOT_FOUND);
}
else
{
BufferedReader br = new BufferedReader((new InputStreamReader(ins)));
String data;
while((data= br.readLine())!= null)
{
out.println(data);
}
}
}
catch(IOException e)
{
out.println(e.getMessage());
}
%>
Code is as follows
var myApp = angular.module("gameModule", []);
myApp.controller("gamecontroller", function ($scope) {
$scope.message = "test";
// websocket connection.
var gameHub = $.connection.socketHub;
$.connection.hub.start().done(function () {
var clientid = $.connection.hub.id;
$(function () {
var user = { signalrsessionid: clientid };
$.ajax({
type: "POST",
data: JSON.stringify(user),
url: "http://localhost:53629/api/game/signalr",
contentType: "application/json"
}).done(function (response) {
alert(response);
$scope.responsemessage = response;
});
});
});
});
and front end code
<!DOCTYPE html>
<html ng-app="gameModule">
<head>
<title>game registration</title>
<meta charset="utf-8" />
<script src="Scripts/jquery-1.10.2.js"></script>
<script src="Scripts/jquery.signalR-2.2.1.js"></script>
<script src="Scripts/angular.js"></script>
<!--Automatisch gegenereerde signalR hub script -->
<script src="signalr/hubs"></script>
<script src="Scripts/rouletteAngular.js"></script>
</head>
<body>
<div ng-controller="gamecontroller">
{{ message }}
{{ responsemessage }}
</div>
So the 'message' is being displayed, the alert box with the response is showing the correct response, but the responsemessage doesnt show any value.
Can anyone tell me what i'm doing wrong.
you must call $scope.$apply(); or $scope.$digest(); after setting $scope.responsemessage = response; because you are using jQuery ajax call, which is outside Angulars context.
EDIT:
here you have nice way to use SignalR in AngularJS:
http://henriquat.re/server-integration/signalr/integrateWithSignalRHubs.html
This is my view and controller. I have converted code from c# to vb the code was working perfectly in C# but i dont know why this java script is not working in vb. I started debugging but controllers never get called when i type something in search box.
Code for View
#ModelType PrudentHealthCare.Product
#Code
Layout = Nothing
End Code
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Search</title>
</head>
<body>
<div>
#Using (Html.BeginForm())
#Html.HiddenFor(Function(model) model.id)
#<input type="text" id="search" placeholder="Search for a product" required />
#<input type="submit" value="Go" id="submit" />
End Using
</div>
</body>
</html>
<link href="~/Content/AutoComplete/jquery-ui.css" rel="stylesheet" />
<script src="~/Content/AutoComplete/jquery-ui.js"></script>
<script src="~/Content/AutoComplete/jquery-1.9.1.js"></script>
<script type="text/javascript">
var url = '#Url.RouteUrl( "DefaultApi" , New With { .httproute = "", .controller = "ProductApi" })';
$('#search').autocomplete({
source: function (request, response) {
$.ajax({
url: url,
data: { query: request.term },
dataType: 'json',
type: 'GET',
success: function (data) {
response($.map(data, function (item) {
return {
label: item.Description,
value: item.Id
}
}));
}
})
},
select: function (event, ui) {
$('#search').val(ui.item.label);
$('#Id').val(ui.item.value);
return false;
},
minLength: 1
});
</script>
ProductApiController
Imports System.Web.Mvc
Namespace Controllers
Public Class ProductApiController
Inherits Controller
<HttpGet>
Public Function GetProducts(Optional query As String = "") As IEnumerable(Of Product)
Dim xyz As String
xyz = query
End Function
End Class
End Namespace
jQuery UI has an AutoComplete widget. The autocomplete widget is quite nice and straight forward to use. In this post, how to integrate the AutoComplete widget with an ASP.NET MVC application.
The first step is to add the jQuery scripts and styles. With ASP.NET MVC 4, the following code does the work:
#Styles.Render("~/Content/themes/base/css")
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/jqueryui")
Using the AutoComplete widget is also simple. You will have to add a textbox and attach the AutoComplete widget to the textbox. The only parameter that is required for the widget to function is source. For this example, we will get the data for the AutoComplete functionality from a MVC action method.
$(document).ready(function () {
$('#tags').autocomplete(
{
source: '#Url.Action("TagSearch", "Home")'
});
})
In the above code, the textbox with id=tags is attached with the AutoComplete widget. The source points to the URL of TagSearch action in the HomeController: /Home/TagSearch. The HTML of the textbox is below:
<input type="text" id="tags" />
When the user types some text in the textbox, the action method - TagSearch is called with a parameter in the request body. The parameter name is term. So, your action method should have the following signature:
public ActionResult TagSearch(string term)
{
// Get Tags from database
string[] tags = { "ASP.NET", "WebForms",
"MVC", "jQuery", "ActionResult",
"MangoDB", "Java", "Windows" };
return this.Json(tags.Where(t => t.StartsWith(term)),
JsonRequestBehavior.AllowGet);
}
I am trying to make the switch in a controller from sending JPA retrieved items as a List to the template engine to now send these as JSON.
I would prefer to use the flexJSON library for the task.
What I have is a Application controller with the method:
public static Result index() {
... Processing ...
flash("success", "Items have been processed");
return ok(index.render(Item.all()));
}
and a view index.scala.html like this one:
#(items: List[Item])
#import helper._
#main("Item list") {
<h1>#items.size() items(s)</h1>
<ul>
#for(item <- items) {
<li>
#item.title
</li>
}
</ul>
}
These to perfectly show an unnumbered list of all the processed items.
Now, if I changed the controller to using flexJSON like so:
public static Result getItems() {
List<Item> items = Item.all();
String s = new JSONSerializer().exclude("*.class", "description").serialize(items);
flash("success", "Messages have been processed");
return ok(index.render(s));
}
How would i program my template in order to consume that json string of items?
i tried to follow this blog on the matter, http://www.jamesward.com/2011/12/11/tutorial-play-framework-jpa-json-jquery-heroku, but fall short on how to consume the json in my template views... any code example would be greatly appreciated.
Just Sample it may help you.
application.conf
db.default.driver=org.h2.Driver
db.default.url="jdbc:h2:mem:play"
ebean.default="models.*"
routes
GET / controllers.Application.index()
GET /cities controllers.Application.all()
Controller => Application.java
package controllers;
import play.*;
import play.mvc.*;
import models.City;
import play.libs.Json;
import views.html.*;
public class Application extends Controller {
public static Result index() {
return ok(index.render());
}
public static Result all(){
City pune=new City();
pune.name="pune";
pune.save();
City mumbai=new City();
mumbai.name="mumbai";
mumbai.save();
return ok(Json.toJson(City.all()));
}
}
Template => index.scala.html
<!DOCTYPE html>
<html>
<head>
<title>Sample</title>
<script src="#routes.Assets.at("javascripts/jquery-1.7.1.min.js")" type="text/javascript"></script>
</head>
<body>
<div id="content"></div>
<script type="text/javascript">
$(function(){
get_cities();
});
var get_cities = function() {
$.ajax({
url: '#routes.Application.all()',
processData:false,
type: 'GET',
beforeSend:function(jqXHR, settings){
jqXHR.setRequestHeader("Content-Type", "application/json");
},
success: function(data, textStatus, jqXHR){
process_cities(data);
},
error: function(jqXHR, textStatus, errorThrown){
},
complete: function(jqXHR,textStatus){
}
});
};
var process_cities = function(cities){
var contentDiv=$("div#content");
contentDiv.append("<ul>");
$.each(cities,function(i,city){
contentDiv.append("<li>" + city.name + "</li>");
});
contentDiv.append("</ul>");
};
</script>
</body>
</html>