Syamkumar K S
Syamkumar K S

Reputation: 119

jsp file upload issues

My code is working fine on local machine. but when I upload it to server it's not working.

Here is my code

html file

<html>
<head>
<form action="fileUpload.jsp" name="upform" enctype="multipart/form-data">
<table width="60%" border="0" cellspacing="1" cellpadding="1" align="center" class="style1">
<tr>
<td align="left"><b>Select a file to upload :</b></td>
</tr>
<tr>
<td align="left">
<input type="file" name="filename" size="50">
</td>
</tr>
<tr>
<td align="left">
<input type="hidden" name="todo" value="upload">
<input type="submit" name="Submit" value="Upload">
<input type="reset" name="Reset" value="Cancel">
</td>
</tr>
</table>
</form>
</body>
</html>

fileUpload.jsp

<%@ page import="java.util.*,java.io.*"%>
<%
String path=request.getParameter("filename");
String newPath="";
int count=0;
try{
if(path!=null)
{
ArrayList arr=new ArrayList();
StringTokenizer st=new StringTokenizer(path,"\\");
while(st.hasMoreTokens())
{
arr.add(count,st.nextToken());
count++;
}
// create ur own path

newPath="/home/sumesh/workspace/TaskManager/WebContent/Pages/Files/"+arr.get(count-1);

int c;
FileInputStream fis=new FileInputStream(path);
FileOutputStream fos=new FileOutputStream(newPath);
while((c=fis.read())!=-1)
{
fos.write((char)c);
}
}
catch (Exception err){
    out.println(err);
}
}
%>

How can I solve this?

Upvotes: 2

Views: 2665

Answers (1)

JB Nizet
JB Nizet

Reputation: 692231

First of all, you should not implement this is a JSP, but in a Servlet (or an action of your favorite MVC framework : Stripes, Spring MVC, Struts, etc.) JSPs are meant for presentatino code only, using HTML, the JSTL and custom JSP tags.

To handle file uploads, you should use a dedicated API such as Apache commons FileUpload, because the servlet API doesn't have direct support for multi-part requests. All MVC frameworks I know about also include support for file uploads.

Now for the explanation of why it works on your local machine : when you open the input stream to the path sent as parameter in the request, you open an input stream using the path of the file on the client's machine. Since in this case, the server machine is also the client machine, it works. But as soon as the server is not the client anymore, it doesn't work anymore.

Upvotes: 2

Related Questions