file upload in strurts 2 - struts2

i need file upload in strurts 2 and store it to server location,i used by googles no use, can anybody give better idea. advance thanks

To google, it might help to check what you type: it's "struts2", no "strurts"
Anyway, you dont need to google, the official docs are enough
http://struts.apache.org/2.2.1/docs/file-upload-interceptor.html
http://struts.apache.org/2.2.1/docs/handling-file-uploads.html
http://cwiki.apache.org/WW/file-upload.html

Here is whole code of struts2 file upload.
Action file (fileupload.java)
package com.tutorialspoint.struts2;
import java.io.File;
import org.apache.commons.io.FileUtils;
import java.io.IOException;
import com.opensymphony.xwork2.ActionSupport;
public class uploadFile extends ActionSupport{
private File myFile;
private String myFileContentType;
private String myFileFileName;
private String destPath;
public String execute()
{
/* Copy file to a safe location */
destPath = "C:/apache-tomcat-6.0.33/work/";
try{
System.out.println("Src File name: " + myFile);
System.out.println("Dst File name: " + myFileFileName);
File destFile = new File(destPath, myFileFileName);
FileUtils.copyFile(myFile, destFile);
}catch(IOException e){
e.printStackTrace();
return ERROR;
}
return SUCCESS;
}
public File getMyFile() {
return myFile;
}
public void setMyFile(File myFile) {
this.myFile = myFile;
}
public String getMyFileContentType() {
return myFileContentType;
}
public void setMyFileContentType(String myFileContentType) {
this.myFileContentType = myFileContentType;
}
public String getMyFileFileName() {
return myFileFileName;
}
public void setMyFileFileName(String myFileFileName) {
this.myFileFileName = myFileFileName;
}
}
index.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>File Upload</title>
</head>
<body>
<form action="upload" method="post" enctype="multipart/form-data">
<label for="myFile">Upload your file</label>
<input type="file" name="myFile" />
<input type="submit" value="Upload"/>
</form>
</body>
</html>
success.jsp
<%# page contentType="text/html; charset=UTF-8" %>
<%# taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<title>File Upload Success</title>
</head>
<body>
You have successfully uploaded <s:property value="myFileFileName"/>
</body>
</html>
Cheers.

Related

Avoid a loop in index page

I have this index.jsp:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
</head>
<body>
<h2>Simple Iterator</h2>
<ol>
<s:iterator value="comboMeals">
<li><s:property /></li>
</s:iterator>
</ol>
<h2>Iterator with IteratorStatus</h2>
<table>
<s:iterator value="comboMeals" status="comboMealsStatus">
<tr>
<s:if test="#comboMealsStatus.even == true">
<td style="background: #CCCCCC"><s:property/></td>
</s:if>
<s:elseif test="#comboMealsStatus.first == true">
<td><s:property/> (This is first value) </td>
</s:elseif>
<s:else>
<td><s:property/></td>
</s:else>
</tr>
</s:iterator>
</table>
</body>
</html>
This is my Java Class:
import java.util.ArrayList;
import java.util.List;
import com.opensymphony.xwork2.ActionSupport;
public class IteratorKFCAction extends ActionSupport{
private List<String> comboMeals;
public List<String> getComboMeals() {
return comboMeals;
}
public void setComboMeals(List<String> comboMeals) {
this.comboMeals = comboMeals;
}
public String execute() {
comboMeals = new ArrayList<String>();
comboMeals.add("Snack Plate");
comboMeals.add("Dinner Plate");
comboMeals.add("Colonel Chicken Rice Combo");
comboMeals.add("Colonel Burger");
comboMeals.add("O.R. Fillet Burger");
comboMeals.add("Zinger Burger");
return SUCCESS;
}
}
My idea was call directly the action that fill the index page, so i put this line inside head tags of index.jsp
<META HTTP-EQUIV="Refresh" CONTENT="0;URL='start.do'">
But with with this fix, i get that the page enter in a "refresh loop". Is there any way to call directly from the code the action, in this way I don't have to set it manually via URL in the browser.
I've tried also a second solution adding to the body of index.jsp this code:
<s:action name="iteratorKFCAction" executeResult="true" />
where iteratorKFCAction is the action specified in struts.xml that recall the IteratorKFCAction. In this case the action loop.
The main purpose of Struts2 (and all other MVC frameworks) is to route the URL to an Action (the Controller) that prepare data (in your case comboMeals) and determine a result (in your case always SUCCESS) that is mapped to a template (the View), in your case index.jsp
In your struts.xml you should have something like
<action name="start.do" class="com.xxx.IteratorKFCAction">
<result name="SUCCESS">/WEB-INF/.../index.jsp</result>
</action>

ExecAndWaitInterceptor doesn't work with Jquery ajax call

I have a working action which is using the ExecAndWait Interceptor. My wait page is
<%# page language="java" pageEncoding="UTF-8" session="false"%>
<%# taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="refresh" content="2"/>"/>
</head>
<body>
<h3>Waiting</h3>
<div id="wait-result">
</div>
</body>
</html>
this is working correctly and adding a breakpoint to my action I can see that the action only gets invoked once regardless of the number of refreshes. As it should.
Now, if I remove the meta-refresh tag and replace it with a JQuery script to
reload the page, what I see is my action gets invoked for each request and the final result page never arrives.
<%# taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js" ></script>
<script>
var repeat = false;
function executeQuery() {
$.ajax({
type: 'GET',
url: 'search',
async: false,
success: function(data) {
if ($(data).find('#wait-result')) {
repeat = true;
} else {
repeat = false;
$('#wait-result').html(data);
}
}
});
if (repeat) {
setTimeout(executeQuery, 1000);
}
}
$(document).ready(function() {
setTimeout(executeQuery, 1000);
});
</script>
</head>
<body>
<h3>Waiting</h3>
<div id="wait-result">
</div>
</body>
</html>
Is it possible to use the ExecAndWait Interceptor with a JQuery Ajax call? If so, what am I doing wrong?
Regards
EDIT
As requested here is the action
package com.harkonnen.actions.search;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import org.apache.log4j.Logger;
import org.apache.struts2.convention.annotation.InterceptorRefs;
import org.apache.struts2.convention.annotation.InterceptorRef;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Results;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import com.harkonnen.services.filter.ZeroResFilter;
import com.harkonnen.services.search.SearchService;
import com.harkonnen.services.search.Town;
#Component
#Scope("protototype")
#Namespace("/search")
#ParentPackage("search")
#InterceptorRefs({
#InterceptorRef(value="secureStack"),
#InterceptorRef(value="execAndWait", params={"delay", "500", "delaySleepInterval","500"}
)
})
#Results({
#Result(name="input", location="start.jsp"),
#Result(name="success", type="redirectAction", location="start" ),
#Result(name="wait", location="wait.jsp")
})
public class Search extends BaseAction {
private int x;
private int y;
private int radius;
private List<Town> towns;
#Autowired
SearchService service;
private static final Logger logger = Logger
.getLogger(Search.class.getName());
public String execute() {
try {
towns = new ZeroResFilter(service.search(x,y,radius)).filter();
System.out.println("Search Complete");
} catch (SQLException e) {
logger.error(e);
addActionError("Sorry, there was an unexpected error with your query.");
return INPUT;
}
if (towns.size() == 0) {
addActionError("There were no results found for the specified search.");
return INPUT;
}
context.setSearchX(x);
context.setSearchY(y);
context.setRadius(radius);
context.setResults(new ArrayList<Town>(towns));
context.setTowns(towns);
return SUCCESS;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public int getRadius() {
return radius;
}
public void setRadius(int radius) {
this.radius = radius;
}
}
The base action
package com.harkonnen.actions.search;
import java.util.Map;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.interceptor.SessionAware;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import com.harkonnen.services.SearchContext;
import com.opensymphony.xwork2.ActionSupport;
#Component
#Scope("protototype")
#Namespace("/search")
public class BaseAction extends ActionSupport implements SessionAware {
protected SearchContext context;
protected boolean isLoggedIn() {
return true;
}
#Override
public void setSession(Map<String, Object> session) {
this.context = (SearchContext) session.get("context");
}
public SearchContext getContext() {
return context;
}
}
The success jsp
<%# page language="java" pageEncoding="UTF-8" session="false"%>
<%# taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE html>
<html>
<head>
<style type="text/css">#import "<%=request.getContextPath()%>/resources/css/global.css";</style>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"></meta>
<title>HoTH Search</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js" ></script>
</head>
<body id="body">
<div id="container">
<div id="login">
<s:action var="login" name="login" executeResult="true"/>
</div>
<div id="perform">
<s:action var="search" name="action-prompt" executeResult="true"/>
<s:actionerror/>
</div>
<div id="results">
<s:action var="results" name="display-search-results" executeResult="true"/>
</div>
<div id="footer-wrapper">
<p>Copyright ©2015 Harkonnen Solutions.</p>
</div>
</div>
</body>
</html>
Ok, found it.
The problem was trying to parse the response to the GET request into an HTML object and then trying to run a selector.
Changing the line
if ($(data).find('#wait-result')) {
to
if (data.indexOf('#wait-result') >=0) {
fixes the problem and now everything runs as expected

Struts2 Pass parameters with NO Session

I have a requirement where passing parameters from one action to another action with No sessions using: Here is my code, I am trying to use scope-interceptor.
here is my code I am not sure what am I doing wrong but I am not able to get the results.
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="default" extends="struts-default">
<action name="HelloWorld" class="com.tutorials4u.helloworld.HelloWorld">
<result name="SUCCESS">/success.jsp</result>
</action>
<action name="FirstAction" class="com.tutorials4u.helloworld.FirstAction">
<interceptor-ref name="basicStack" />
<interceptor-ref name="scope">
<param name="session">myName</param>
<param name="key">person</param>
<param name="type">start</param>
</interceptor-ref>
<result name="SUCCESS">/success1.jsp</result>
</action>
<action name="SecondAction" class="com.tutorials4u.helloworld.SecondAction">
<interceptor-ref name="scope">
<param name="session">myName</param>
<param name="key">person</param>
</interceptor-ref>
<interceptor-ref name="basicStack" />
<result name="SUCCESS">/success2.jsp</result>
</action>
</package>
</struts>
*index.jsp*
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<%#taglib uri="/struts-tags" prefix="s" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Hello World</title>
</head>
<body>
<s:form action="HelloWorld" >
<s:textfield name="userName" label="User Name" />
<s:submit />
</s:form>
</body>
</html>
*Success.jsp*
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<%#taglib uri="/struts-tags" prefix="s" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Hello World</title>
</head>
<body>
<s:property value="person.myName"></s:property>
<s:form action="FirstAction" >
<s:submit value="Click for first Action"></s:submit>
</s:form>
</body>
</html>
*success1.jsp*
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<%#taglib uri="/struts-tags" prefix="s" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Hello World</title>
</head>
<body>
<s:property value="person.myName"></s:property>
<h1><s:property value="message" /></h1>I am in FIRST ACTION
<s:form action="SecondAction">
<s:submit value="click for 2nd action"></s:submit></s:form>
</body>
</html>
*success2.jsp*
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<%#taglib uri="/struts-tags" prefix="s" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Hello World</title>
</head>
<body>
<h1><s:property value="message" /></h1>2ND ACTION EXECUTED
<s:property value="person.myName"></s:property>
</body>
</html>
**ACTIONS**
package com.tutorials4u.helloworld;
import com.opensymphony.xwork2.ActionSupport;
/**
*
*
*/
public class HelloWorld extends ActionSupport{
private static final long serialVersionUID = 1L;
private String message;
private String userName;
public HelloWorld() {
}
public String execute() {
setMessage("Hello " + getUserName());
return "SUCCESS";
}
/**
* #return the message
*/
public String getMessage() {
return message;
}
/**
* #param message the message to set
*/
public void setMessage(String message) {
this.message = message;
}
/**
* #return the userName
*/
public String getUserName() {
return userName;
}
/**
* #param userName the userName to set
*/
public void setUserName(String userName) {
this.userName = userName;
}
}
*FirstAction.java*
package com.tutorials4u.helloworld;
import com.opensymphony.xwork2.ActionSupport;
public class FirstAction extends ActionSupport {
/**
*
*/
private String myString;
private Person person;
private static final long serialVersionUID = 1L;
public FirstAction(){
}
public String execute() {
return "SUCCESS";
}
public String getMyString() {
return myString;
}
public void setMyString(String myString1) {
this.myString = myString1;
}
public Person getPerson() {
return person;
}
public void setPerson(Person person) {
this.person = person;
}
}
package com.tutorials4u.helloworld;
public class Person {
private String myName;
public String getMyName() {
return myName;
}
public void setMyName(String myName1) {
myName1 = "test string";
this.myName = myName1;
}
}
SecondAction.java
package com.tutorials4u.helloworld;
import com.opensymphony.xwork2.ActionSupport;
public class SecondAction extends ActionSupport {
private static final long serialVersionUID = 1L;
private Person person;
public SecondAction(){
}
public String execute() {
return "SUCCESS";
}
public Person getPerson() {
return person;
}
public void setPerson(Person person) {
this.person = person;
}
}
---I would really appreciate if you can help me on where I was doing things wrong..
TIA
so we are instantiating session object in each and every other action
right?
Not at all, we are just retrieving it from the ServletActionContext.
How to put in session
ServletActionContext.getContext().getSession().put("softuser", someUserObject);
How to retrieve from session
ServletActionContext.getContext().getSession().get("softuser");

Problems with Login application in struts2

I am trying to write small login application in struts 2.Session is b eing created successfully.In welcome.jsp "logout" option is given.On logout control will be redirected to Logout.jsp.
My problem is after logout session variables are destroyed but pages are storing in browser cache.If click back button of browser i am able to see welcome.jsp.
For clearing cache "ClearCacheInterceptor" is used.I don't understand where i am making mistake.
Instead of clearing browser every time is there any to overcome this prooblem ? Is my approach correct ? Please suggest me.
Login.jsp
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%#taglib uri="/struts-tags" prefix="s" %>
<!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=UTF-8">
<title>Login</title>
</head>
<body>
<s:form action="login">
<s:textfield name="myname"></s:textfield>
<s:submit value="submit"></s:submit>
</s:form>
</body>
</html>
Struts.xml
<interceptors>
<interceptor name="clear-cache" class="ActionClasses.ClearCacheInterceptor" />
</interceptors>
<action name="login" class="ActionClasses.LoginAction" >
<interceptor-ref name="clear-cache" />
<result name="success">Welcome.jsp</result>
<result name="error">Login.jsp</result>
</action>
<action name="logout" class="ActionClasses.Logout">
<interceptor-ref name="clear-cache" />
<result name="success">Logout.jsp</result>
</action>
LoginAction.java
package ActionClasses;
import java.util.Map;
import org.apache.struts2.interceptor.SessionAware;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.validator.annotations.RequiredFieldValidator;
import com.opensymphony.xwork2.validator.annotations.ValidatorType;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.interceptor.Interceptor;
public class LoginAction extends ActionSupport implements SessionAware
{
/**
*
*/
private static final long serialVersionUID = 1L;
private String myname;
private Map<String , Object> s;
public String execute()throws Exception
{
s=ActionContext.getContext().getSession();
s.put("login", myname);
return "success";
}
public void setMyname(String s)
{
myname=s;
}
public String getMyname()
{
return myname;
}
#Override
public void setSession(Map<String, Object> arg0) {
// TODO Auto-generated method stub
s=arg0;
}
}
ClearcacheInterceptor.java
package ActionClasses;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.StrutsStatics;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
public class ClearCacheInterceptor extends AbstractInterceptor{
/**
*
*/
private static final long serialVersionUID = 1L;
#Override
public String intercept(ActionInvocation invocation) throws Exception {
ActionContext context=(ActionContext)invocation.getInvocationContext();
HttpServletResponse response=(HttpServletResponse)context.get(StrutsStatics.HTTP_RESPONSE);
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Pragma", "no-cache");
response.setDateHeader("Expires", 0);
String result=invocation.invoke();
System.out.println("check result="+result);
return result;
}
}
Logout.java
package ActionClasses;
import java.util.Map;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class Logout extends ActionSupport {
public String execute(){
Map<String,Object> s=ActionContext.getContext().getSession();
s.remove("login");
ActionContext.getContext().getSession().clear();
return "success";
}
}
Welcome.jsp
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%# page contentType="text/html; charset=UTF-8"%>
<%# taglib prefix="s" uri="/struts-tags"%>
<s:include value="CheckLogin.jsp"></s:include>
<%# taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
</head>
<body>
<font color="white"></font>
Welcome<s:property value="#session['login']"/>
<s:a href="logout">Logout</s:a>
</body>
</html>
Logout.jsp
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%# taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
log out successful !!
</body>
</html>
CheckLogin.jsp
<%# taglib prefix="s" uri="/struts-tags" %>
<%# page language="java" contentType="text/html" import="java.util.*"%>
<html>
<head>
<title>Check validate!</title>
</head>
<body>
This is session validation page!
<s:if test="#session.login != 'Jagan'">
<jsp:forward page="Login.jsp" />
</s:if>
</body>
</html>
Well that's a very common issue and this is with respect to your browser cache issue rather than struts2 or any other framework at all.
we have face same problem since when you hit the back button of browser the request is not being send to the server rather it is being serves from the browser cache.you will only notice things when you try to do some work and it will come up with error that you are no longer being logged in.
though you can use certain header like no-cache etc but they are being obeyed by the browser is not certain.
only workaround to this problem as per my understanding is to use https (secure browsing) for your work and than use the header (no-cache. cache-expiry etc) since when you browse application under secure mode these header will be followed by the server and browser.
i hope this will try to give you an idea, just to check redirect to https protocol when your logout and it will solve your problem

How To Upload Image

I am getting the following error whilst uploading a file.
The parameters dictionary contains a
null entry for parameter 'category_id'
of non-nullable type 'System.Int32'
for method
'System.Web.Mvc.ActionResult
AddProduct(Int32, System.String,
Single, System.String, System.String,
System.String, System.String,
System.String, System.String)' in
'Ecommerce.Controllers.AdminController'.
To make a parameter optional its type
should be either a reference type or a
Nullable type. Parameter name:
parameters
I am using a dialog box.
The View
<script type="text/javascript">
$(function() {
$("#dialog").dialog({
bgiframe: true,
height: 140,
modal: true,
autoOpen: false,
resizable: false
})
});
</script>
<div id="dialog" title="Upload files">
<% using (Html.BeginForm("Upload", "File", FormMethod.Post, new { enctype = "multipart/form-data" }))
{%>
<p><input type="file" id="fileUpload" name="fileUpload" size="23"/> </p>
<p><input type="submit" value="Upload file" /></p>
<% } %>
</div>
<p>
<label for="image_name">image_name:</label>
Upload File
<%= Html.ValidationMessage("image_name", "*") %>
</p>
The Controller Action
public ActionResult AddProduct(int category_id, string product_name, float product_price, string product_desc, string weight, string image_name, string img_content, string available_qty, string isFeature)
{
foreach (string inputTagName in Request.Files)
{
HttpPostedFileBase file = Request.Files[inputTagName];
if (file.ContentLength > 0)
{
string filePath = Path.Combine(HttpContext.Server.MapPath("../Uploads"), Path.GetFileName(file.FileName));
string filecontent = Path.Combine(HttpContext.Server.MapPath("../Uploads"), Path.GetFileName(file.ContentType));
image_name = Path.GetFileName(file.FileName);
img_content = Path.GetFileName(file.ContentType);
file.SaveAs(filePath);
}
}
AdminImplementation _adminImplementation = new AdminImplementation();
Boolean isfeature = Convert .ToBoolean(isFeature);
if (isfeature)
{
isFeature = "Featured";
}
else
{
isFeature = "NotFeatured";
}
int i = _adminImplementation.addproduct(category_id, product_name, product_price, product_desc, weight,image_name ,img_content ,available_qty ,isFeature );
ViewData["succm"] = "Product added successfully";
return View();
}
Please suggest some useful answers.
Thanks
Ritz
Looks to me like you're not providing all the parameters required for a specific ActionResult. category_id isn't being provided to AddProduct. You'd need to show us your code for us to be able to find out what's really going wrong.
How are you calling that ActionResult?
**UPLOADING IMAGE AND SAVING PATH IN THE DATABASE
________________________________________________________________________________________
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>Insert title here</title>
</head>
<body>
<div>
<h3> Choose File to Upload in Server </h3>
<form action="Recent" method="post" enctype="multipart/form-data">
<input type="file" name="file" />
<input type="submit" value="upload" />
</form>
</div>
</body>
</html>
____________________________________________________________________________________________
import java.sql.*;
import java.io.*;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import java.util.Hashtable;
import java.util.List;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.ParameterParser;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
/**
* Servlet implementation class Recent
*/
#WebServlet("/Recent")
#MultipartConfig
public class Recent extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public Recent() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
Sample s1=new Sample();
final String UPLOAD_DIRECTORY = "/home/pradeep/Documents/pradeep/WebContent/Images";
if(ServletFileUpload.isMultipartContent(request)){
try {
List<FileItem> multiparts = new
ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
for(FileItem item : multiparts){
if(!item.isFormField())
{
String name = new File(item.getName()).getName();
item.write( new File(UPLOAD_DIRECTORY + File.separator + name));
String Path= "/home/pradeep/Documents/pradeep/WebContent/Images/" +name;
s1.connecting(Path);
}
}
request.setAttribute("message", "File Uploaded Successfully");
} catch (Exception ex) {
request.setAttribute("message", "File Upload Failed due to " + ex);
}
}else{
request.setAttribute("message",
"Sorry this Servlet only handles file upload request");
}
request.getRequestDispatcher("/Result.jsp").forward(request, response);
}
}
__________________________________________________________________________________________
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import dbconnections.Connections;
public class Sample {
Connections con=new Connections();
public void connecting(String Path)
{
Connection conn=con.Connect();
PreparedStatement pst;
String query="INSERT INTO Student1 (Path) values (?)";
try {
pst=conn.prepareStatement(query);
pst.setString(1,Path);
pst.executeUpdate();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// TODO Auto-generated method stub
}
}

Resources