jsp servlet Etat HTTP 404 [duplicate] - servlets

This question already has answers here:
Servlet returns "HTTP Status 404 The requested resource (/servlet) is not available"
(19 answers)
Closed 5 years ago.
i have this trouble when i programming this:
Etat HTTP 404 - /IT/UserServlet
type Rapport d''état
message /IT/UserServlet
description La ressource demandée n''est pas disponible.
Apache Tomcat/8.0.27
this is my code:
register.jsp
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Register Page</title>
<script src="https://s.codepen.io/assets/libs/modernizr.js" type="text/javascript"></script>
<link rel="stylesheet" href="css/register_style.css">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
var x_timer;
$("#username").keyup(function (e) {
clearTimeout(x_timer);
var user_name = $(this).val();
x_timer = setTimeout(function () {
check_username_ajax(user_name);
}, 1000);
});
function check_username_ajax(username) {
$("#user-result").html('<img src="img/ajax-loader.gif" />');
$.post('CheckUserNameServlet', {'username': username}, function (data) {
$("#user-result").html(data);
});
}
});
</script>
</head>
<body>
<form action="UserServlet" method="POST">
<h1>Sign up</h1><br/>
<span class="input"></span>
<input type="text" name="name" id = "name" placeholder="Full name" autofocus autocomplete="off" />
<span class="input" ></span>
<input type="text" name="username" id="username" placeholder="username" />
<span id = "user-result"></span>
<span id="passwordMeter"></span>
<input type="password" name="password" id="password" placeholder="Password" title="Password min 8 characters. At least one UPPERCASE and one lowercase letter" required pattern="(?=^.{8,}$)(?=.*[a-z])(?=.*[A-Z])(?!.*\s).*$"/>
<input type="hidden" value="insert" name="command">
<button type="submit" value="Sign Up" title="Submit form" class="icon-arrow-right"><span>Sign up</span></button>
</form>
</body>
and this is sevlet:
public class UserServlet extends HttpServlet {
UserDAO userDao = new UserDAO();
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//processRequest(request, response);
String command = request.getParameter("command");
String url="";
switch(command){
case"insert":
User user = new User();
user.setUserId(new Date().getTime());
user.setName(request.getParameter("name"));
user.setUserName(request.getParameter("username"));
user.setPassword(request.getParameter("password"));
user.setCreateTime(Date.from(Instant.now()));
user.setUpdateTime(Date.from(Instant.now()));
userDao.InsertUser(user);
HttpSession session = request.getSession();
session.setAttribute("user", user);
url = "index.jsp";
break;
}
RequestDispatcher rd = getServletContext().getRequestDispatcher(url);
rd.forward(request, response);
}
}
this is UseDAO:
public boolean InsertUser(User u) {
Connection conn = Connect.getConnecttion();
String insert_user = "INSERT INTO user(name, user_name, password, role, create_time, update_time) values(?,?,?,?,?,?)";
try {
PreparedStatement ps = conn.prepareStatement(insert_user);
ps.setString(1, u.getName());
ps.setString(2, u.getUserName());
ps.setString(3, u.getPassword());
ps.setInt(4, 4);
ps.setDate(5, Date.valueOf(LocalDate.now()));
ps.setDate(6, Date.valueOf(LocalDate.now()));
ps.executeUpdate();
return true;
} catch (SQLException ex) {
Logger.getLogger(UserDAO.class.getName()).log(Level.SEVERE, null, ex);
}
return false;
}
my web.xml:
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>Controller.UserServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>CheckUserNameServlet</servlet-name>
<servlet-class>Controller.CheckUserNameServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/LoginServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>CheckUserNameServlet</servlet-name>
<url-pattern>/CheckUserNameServlet</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
</web-app>
when i run test register.jsp and it show me the error but i don't know where, so please help!

Based on the added web.xml, you have mapped the URL to /LoginServlet, not /UserServlet you are trying to access.
Also make sure, that the context-path (/IT) is correct in your server.

Related

Adding Shiro to the Eclipse java project - no error message at all for diagnosis

I have just added Shiro to the project, adding two jars to the WEB-INF/lib (shiro-core and shiro-web), customizing the web.xml, and adding shiro.ini in the WEB-INF folder. I have also written an ad hoc menu.jsp with the login form using shiro:guest tags. The problem is that , when I launch the application, and insert the username and password into the form, in order to login, nothing happen and really no message is displayed in the console. So it is difficult for me to do a diagnosis of the problem. What should I do in order to proceed ?
web.xml is the following:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
<display-name>photoalbum</display-name>
<servlet>
<servlet-name>action</servlet-name>
<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
<init-param>
<param-name>config</param-name>
<param-value>/WEB-INF/struts/struts-config.xml</param-value>
</init-param>
<init-param>
<param-name>chainConfig</param-name>
<param-value>org/apache/struts/tiles/chain-config.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<listener>
<listener-class>it.univaq.mwt.bcd.photoalbum.common.startup.PhotoAlbumServletContextListener</listener-class>
</listener>
<listener>
<listener-class>org.apache.shiro.web.env.EnvironmentLoaderListener</listener-class>
</listener>
<filter>
<filter-name>ShiroFilter</filter-name>
<filter-class>org.apache.shiro.web.servlet.ShiroFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>ShiroFilter</filter-name>
<url-pattern>*.do</url-pattern>
<dispatcher>REQUEST</dispatcher>
<dispatcher>FORWARD</dispatcher>
<dispatcher>INCLUDE</dispatcher>
<dispatcher>ERROR</dispatcher>
</filter-mapping>
<welcome-file-list>
<welcome-file>index.do</welcome-file>
</welcome-file-list>
</web-app>
the shiro.ini is the following
[main]
authc.loginUrl = /index.do
authc.successUrl = /common/welcome.do
myroles= it.univaq.mwt.bcd.photoalbum.common.shiro.MyRolesAuthorizationFilter
myRealm = it.univaq.mwt.bcd.photoalbum.common.shiro.MyAuthorizingRealm
securityManager.realms = $myRealm
[users]
#borrower = borrower, borrower
#librarian = librarian, librarian
#masterlibrarian = masterlibrarian, masterlibrarian
#RegisteredUser = RegisteredUser
[roles]
#borrower = *
#librarian = *
#masterlibrarian = *
#RegisteredUser = *
[urls]
/index.do = authc
/logout.do = logout
/common/** = authc, myroles[librarian, masterlibrarian, borrower, RegisteredUser]
/titles/** = authc, myroles[librarian,masterlibrarian, RegisteredUser]
/borrowers/** = authc, myroles[librarian, masterlibrarian, RegisteredUser]
/items/** = authc, myroles[librarian, masterlibrarian, RegisteredUser]
/librarians/** = authc, myroles[masterlibrarian, RegisteredUser]
/items/checkoutitem.do = authc, myroles[borrower]
/items/returntitem.do = authc, myroles[borrower]
the menu.jsp is the following:
<%#taglib uri="http://shiro.apache.org/tags" prefix="shiro"%>
<%#taglib uri="http://struts.apache.org/tags-bean" prefix="bean"%>
<div class="navbar navbar-inverse navbar-fixed-top" >
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="${pageContext.request.contextPath}/common/welcome.do"><bean:message key="common.title" /></a>
</div>
<div class="navbar-collapse collapse">
<shiro:authenticated>
<ul class="nav navbar-nav">
<li class="dropdown"><bean:message key="menu.home" /><b class="caret"></b>
<ul class="dropdown-menu">
<li> <a
href="${pageContext.request.contextPath}/registered/profile.do">
<bean:message key="menu.profile" />
</a>
</li>
<li>
<a
href="${pageContext.request.contextPath}/registered/uploadform.do">
<bean:message key="menu.upload" />
</a>
</li>
</ul>
</li>
<shiro:hasRole name="RegisteredUser">
<li><bean:message key="menu.list" /></li>
<li><bean:message key="menu.comment" /></li>
<li><bean:message key="menu.gallery" /></li>
</shiro:hasRole>
<shiro:hasRole name="Admin">
</shiro:hasRole>
<li><bean:message key="menu.logout" /></li>
</ul>
</shiro:authenticated>
<shiro:guest>
<form name="loginform" action="${pageContext.request.contextPath}/index.do" method="post" class="navbar-form navbar-right" >
<div class="form-group">
<input type="text" placeholder="Username" class="form-control" name="j_username">
</div>
<div class="form-group">
<input type="password" placeholder="Password" class="form-control" name="j_password">
</div>
<button type="submit" class="btn btn-success">
<bean:message key="common.signin" />
</button>
</form>
</shiro:guest>
</div>
<!--/.navbar-collapse -->
</div>
</div>
I also have this two java programs (not by me) that make to work the shiro.ini
package it.univaq.mwt.bcd.photoalbum.common.shiro;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import it.univaq.mwt.bcd.photoalbum.business.BusinessException;
import it.univaq.mwt.bcd.photoalbum.business.LibraryBusinessFactory;
import it.univaq.mwt.bcd.photoalbum.business.PhotoAlbumBusinessFactory;
import it.univaq.mwt.bcd.photoalbum.business.SecurityService;
import it.univaq.mwt.bcd.photoalbum.business.model.Role;
import it.univaq.mwt.bcd.photoalbum.business.model.User;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.Permission;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
public class MyAuthorizingRealm extends AuthorizingRealm {
#Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
UsernamePasswordToken upToken = (UsernamePasswordToken) token;
SecurityService service = PhotoAlbumBusinessFactory.getInstance().getSecurityService();
User user = null;
try {
user = service.authenticate(upToken.getUsername());
} catch (BusinessException idEx) {
throw new AuthenticationException(idEx);
}
if (user == null) {
throw new AuthenticationException("Login name [" + upToken.getUsername() + "] not found!");
}
return new SimpleAuthenticationInfo(user, user.getPassword(), getName());
}
#Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
Set<String> roles = new HashSet<String>();
Set<Permission> permissions = new HashSet<Permission>();
Collection<User> principalsList = principals.byType(User.class);
if (principalsList.isEmpty()) {
throw new AuthorizationException("Empty principals list!");
}
SecurityService service = PhotoAlbumBusinessFactory.getInstance().getSecurityService();
//LOADING STUFF FOR PRINCIPAL
for (User userPrincipal : principalsList) {
try {
User user = service.authenticate(userPrincipal.getUsername());
Set<Role> userRoles = user.getRoles();
for (Role r : userRoles) {
roles.add(r.getName());
}
} catch (BusinessException idEx) { //userManger exceptions
throw new AuthorizationException(idEx);
}
}
//THIS IS THE MAIN CODE YOU NEED TO DO !!!!
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(roles);
info.setRoles(roles); //fill in roles
info.setObjectPermissions(permissions); //add permissions (MUST IMPLEMENT SHIRO PERMISSION INTERFACE)
return info;
}
}
and the following :
package it.univaq.mwt.bcd.photoalbum.common.shiro;
import java.io.IOException;
import java.util.Set;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.CollectionUtils;
import org.apache.shiro.web.filter.authz.AuthorizationFilter;
public class MyRolesAuthorizationFilter extends AuthorizationFilter {
#SuppressWarnings({"unchecked"})
public boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws IOException {
Subject subject = getSubject(request, response);
String[] rolesArray = (String[]) mappedValue;
if (rolesArray == null || rolesArray.length == 0) {
//no roles specified, so nothing to check - allow access.
return true;
}
Set<String> roles = CollectionUtils.asSet(rolesArray);
for (String role : roles) {
if (subject.hasRole(role)) {
return true;
}
}
return false;
}
}
My only doubt is if these two java programs fits for my application (I used these two java programs in another java project and they worked)! Please help me ! Thanks.
It could be that you are the victim of the following bug:
https://issues.apache.org/jira/browse/SHIRO-467
Authentication exceptions which could happen in your custom realm get swallowed by shiro.
There is a workaround to get the exception thrown which worked for us. If you can get a hold of the securityManager object somewhere in a startup method (we use spring, so we use a configuration class, but you might be able to use a servlet context listener or something like that).
On the security manager, register an authentication listener like so:
AbstractAuthenticator abstractAuthenticator = (AbstractAuthenticator) securityManager.getAuthenticator();
abstractAuthenticator.getAuthenticationListeners().add(new AuthenticationListener() {
#Override
public void onSuccess(AuthenticationToken token, AuthenticationInfo info) {
}
#Override
public void onFailure(AuthenticationToken token, AuthenticationException ae) {
if (ae.getCause() != null) {
//log exception or do ae.printStackTrace(), we log it:
LOG.error("Problem during authenticating {}", token, ae);
}
}
#Override
public void onLogout(PrincipalCollection principals) {
}
});

#WebServlet annotation with tomcat 6

I tried to write a simple web application using servlet. when I tried to execute the frist page it get executed with the url "//localhost:8080/PassingParameter/ParamHtml.html" correctly. When I click the next button the url is changing too "localhost:8080/ReadParamUrl/*"
In my servlet code is
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html");
PrintWriter out=response.getWriter();
String title = "Reading All Form Parameters";
String docType =
"<!doctype html public \"-//w3c//dtd html 4.0 " +
"transitional//en\">\n";
out.println(docType +
"<html>\n" +
"<head><title>" + title + "</title></head>\n" +
"<body bgcolor=\"#f0f0f0\">\n" +
"<h1 align=\"center\">" + title + "</h1>\n" +
"<table width=\"100%\" border=\"1\" align=\"center\">\n" +
"<tr bgcolor=\"#949494\">\n" +
"<th>Param Name</th><th>Param Value(s)</th>\n"+
"</tr>\n");
Enumeration<?> paramNames = request.getParameterNames();
while(paramNames.hasMoreElements()) {
String paramName = (String)paramNames.nextElement();
out.print("<tr><td>" + paramName + "</td>\n<td>");
String[] paramValues =
request.getParameterValues(paramName);
// Read single valued data
if (paramValues.length == 1) {
String paramValue = paramValues[0];
if (paramValue.length() == 0)
out.println("<i>No Value</i>");
else
out.println(paramValue);
} else {
// Read multiple valued data
out.println("<ul>");
for(int i=0; i < paramValues.length; i++) {
out.println("<li>" + paramValues[i]);
}
out.println("</ul>");
}
}
out.println("</tr>\n</table>\n</body></html>");
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
The xml code is
<welcome-file>ParamHtml.html</welcome-file>
</welcome-file-list>
<servlet>
<description></description>
<display-name>ReadParam</display-name>
<servlet-name>ReadParam</servlet-name>
<servlet-class>org.param.ReadParam</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ReadParam</servlet-name>
<url-pattern>/ReadParamUrl</url-pattern>
</servlet-mapping>
The html code is
<form action="/ReadParamUrl" method="POST" target="_blank">
<input type="checkbox" name="maths" checked="checked" /> Maths
<input type="checkbox" name="physics" /> Physics
<input type="checkbox" name="chemistry" checked="checked" /> Chemistery
<input type="submit" value="Select Subject" />
</form>
I hope I have given the url correct, but it is not working.
Please help me..
If you want to use servlet-3.0 and #WebServlet then you must use Tomcat 7 or later.

uploading image in db2 with a servlet

i am trying to upload image into my db2 database.i have copied the libraries required
db2jcc.jar in web-inf/lib
<form action="Upload" method="post" enctype="multipart/form-data">
ID : <input type="text" name="id"/><br>
FILE : <input type="file" name="photo"/><br>
<input type="submit" value="upload"/>
</form>
my uploader servlet is
try {
String id=request.getParameter("id");
Part photo = request.getPart("photo");
try
{
Class.forName("com.ibm.db2.jcc.DB2Driver").newInstance();
Connection con=DriverManager.getConnection("jdbc:db2:SAMPLEDB");
System.out.println("Connection Successful");
PreparedStatement ps=con.prepareStatement("INSERT INTO SAMPLETABLE (ID,PHOTO) VALUES (?,?)");
ps.setString(1, id);
File fBlob = new File ( request.getParameter("photo") ); //exception thrown here
FileInputStream is = new FileInputStream ( fBlob );
ps.setBinaryStream (2, is, (int) fBlob.length() );
ps.execute ();
}
catch(Exception e)
{
System.out.println("exception --> "+e);
}
}
finally
{
out.close();
}
}
the exception i am getting is
java.lang.NullPointerException
The request.getParameter() and its related methods do not work with multi-part requests, and will always return null when dealing with multipart form data.
See the following on File Uploads in Java:
https://www.coderanch.com/how-to/java/FileUpload
Here's even a better solution: http://www.roseindia.net/jsp/file_upload/Sinle_upload.xhtml.shtml

Unable to send message to group in SignalR

I am using SignalR library. I am running 3 instances of my application and then I add two users to a group named 'Test'. Now when i send message to 'Test' group, the message is not delivered at all.
public class ChatHub : Hub
{
public void send(string name, string message)
{
//This line of code is not working
Clients.Group("test").broadcastMessage(message);
//This is working
//Clients.All.broadcastMessage(name, message);
}
public void JoinGroup(string groupName)
{
Groups.Add(this.Context.ConnectionId, groupName);
}
public void RemoveGroup(string groupName)
{
Groups.Remove(this.Context.ConnectionId, groupName);
}
}
//Client side
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>SignalR Simple Chat</title>
<style type="text/css">
.container {
background-color: #99CCFF;
border: thick solid #808080;
padding: 20px;
margin: 20px;
}
</style>
</head>
<body>
<div class="container">
<input type="text" id="groupName" />
<input type="button" id="joinGroup" value="Join" />
<br />
<input type="text" id="message" />
<input type="button" id="sendmessage" value="Send" />
<input type="hidden" id="displayname" />
<ul id="discussion">
</ul>
</div>
<script type="text/javascript" src="Scripts/jquery-1.6.4.min.js"></script>
<script type="text/javascript" src="Scripts/j`enter code here`query.signalR-1.0.0-rc1.js"></script>
<script type="text/javascript" src="/signalr/hubs"></script>
</body>
<script type="text/javascript">
$(function () {
// Declare a proxy to reference the hub.
var chat = $.connection.chatHub;
// Create a function that the hub can call to broadcast messages.
chat.client.broadcastMessage = function (name, message) {
// Html encode display name and message.
var encodedName = $('<div />').text(name).html();
var encodedMsg = $('<div />').text(message).html();
// Add the message to the page.
$('#discussion').append('<li><strong>' + encodedName
+ '</strong>: ' + encodedMsg + '</li>');
};
// Get the user name and store it to prepend to messages.
$('#displayname').val(prompt('Enter your name:', ''));
// Set initial focus to message input box.
$('#message').focus();
// Start the connection.
$.connection.hub.start().done(function () {
$('#sendmessage').click(function () {
// Call the Send method on the hub.
chat.server.send($('#displayname').val(), $('#message').val());
// Clear text box and reset focus for next comment.
$('#message').val('').focus();
});
$('#joinGroup').click(function () {
// Call the Send method on the hub.
chat.server.joinGroup($('#groupName').val());
});
});
});
</script>
</html>
Actually the 'broadcastMessage' on the client was expecting two parameter and i was passing only one parameter while calling 'broadcastMessage' using group.
Changing
'Clients.Group("test").broadcastMessage(message);'
to
'Clients.Group("test").broadcastMessage(name, message);' worked.

How to pass file content into [WebMethod] with jquery uploadify plugin

I would like to pass file content into [WebMethod] with jquery uploadfy plugin
But the Upload method can not be invoked.Can anyone help me out? Thanks in advance!
Index.aspx:
<head runat="server">
<title></title>
<link href="uplodify/uploadify.css" rel="stylesheet" type="text/css" />
<script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
<script src="uplodify/swfobject.js" type="text/javascript"></script>
<script src="uplodify/jquery.uploadify.v2.1.4.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#file_upload').uploadify({
'uploader': '/uplodify/uploadify.swf',
'script': '/Index.aspx/Upload',
'cancelImg': '/uplodify/cancel.png',
'buttonImg': '/uplodify/browse.jpg',
'sizeLimit': 262144,
'fileExt': '*.jpg',
'fileDesc': '*.jpg',
'folder': '/pic',
'onProgress': function (event, ID, fileObj, data) {
var bytes = Math.round(data.bytesLoaded / 1024);
$('#' + $(event.target).attr('id') + ID).find('.percentage').text(' - ' + bytes + 'KB ');
return false;
},
'onSelect': function (event, ID, fileObj) {
if (parseInt(fileObj.size) > 262144) {
window.alert fileObj.name");
return false;
}
},
'onComplete': fun
});
});
function checkImport() {
if ($.trim($('#file_uploadQueue').html()) == "") {
alert('please select pic!');
return false;
}
else {
jQuery('#file_upload').uploadifyUpload();
return true;
}
}
function fun(event, queueID, fileObj, response, data) {
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<img height="100" width="100" src="nopic.jpg" id="filesUploaded" runat="server" />
<input id="file_upload" name="file_upload" type="file" />
<input id="Button1" type="button" value="uploadfile" onclick="checkImport()" runat="server"
class="ui-corner-all" /><br />
</div>
</form>
</body>
Index.cs:
public partial class Index : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static string Upload(byte[] FileData)
{
return "";
}
}
In ASP.NET Page methods expect to be invoked using application/json content type. So you could use either a new WebForm or a generic handler to handle the file upload:
$(document).ready(function () {
$('#file_upload').uploadify({
'swf': '<%= ResolveUrl("~/uploadify/uploadify.swf") %>',
'uploader': '<%= ResolveUrl("~/upload.ashx") %>'
});
});
and the generic handler might look like this:
public class Upload : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
HttpPostedFile uploadedFile = context.Request.Files["FileData"];
// TODO: do something with the uploaded file. For example
// you could access its contents using uploadedFile.InputStream
context.Response.ContentType = "text/plain";
context.Response.Write("Hello World");
}
public bool IsReusable
{
get { return true; }
}
}
Also to facilitate debugging use a tool such as Fiddler as it allows you to inspect the HTTP traffic between the client and the web server, showing you potential errors you might have. Also a javascript debugging tool such as FireBug or Chrome developer tools is a must-have.

Resources