Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Want to add file upload functionality to application

Status
Not open for further replies.

dognobbler

Programmer
Jul 4, 2003
46
GB
I have a application running on tomcat that I wish to add a file upload functionality to. I have done some research but am having difficulty finding a method that I can understand.

I am a beginner and I have looked at the O Reilly Cos class offered here

but could not find any kind of tutorial on how to use this class once you had it installed.

Can anyone recommend a file upload facility that has decent enough support files to allow a beginner to implement it.

Thanks


Andy
 
I also found that example overcomplicated. Below is the servlet class I use - you'll be able to do away with some of the request.getParameters (the stuff to do with "quickTip" etc, depending on how your client page looks. Also below is the client code you need which hits the servlet....


import java.io.*;
import java.util.*;

import javax.servlet.http.*;
import javax.servlet.*;


public class UploadServlet extends HttpServlet {
String to = null;
String data = null;
ServletContext servletContext;

public void init(ServletConfig servletConfig) throws ServletException {
super.init( servletConfig );
servletContext = servletConfig.getServletContext();
System.out.println("Initializing ...");
}

public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}

public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
HttpSession session = req.getSession(true);
PrintWriter out = null;
DataInputStream in = null;
FileOutputStream fileOut = null;
String rootPath = (String)session.getAttribute("fileNamePathToSaveTo");
String fileName = null;
//int MAX_SIZE = 50 * 1024; // 50 Mb
try {
resp.setContentType("text/html");
String contentType = req.getContentType();
System.out.println("Content type is :: " +contentType);
//java.util.Enumeration enum = req.getParameterNames();
//while(enum.hasMoreElements()) {
// System.out.println(" param = " + (String)enum.nextElement());
//}

if ((contentType != null) && (contentType.indexOf("multipart/form-data") >= 0)) {
in = new DataInputStream(req.getInputStream());
int formDataLength = req.getContentLength();

byte dataBytes[] = new byte[formDataLength];
int byteRead = 0;
int totalBytesRead = 0;
while (totalBytesRead < formDataLength) {
byteRead = in.read(dataBytes, totalBytesRead, formDataLength);
totalBytesRead += byteRead;
}

String file = new String(dataBytes);
String saveFile = file.substring(file.indexOf(&quot;filename=\&quot;&quot;) + 10);
saveFile = saveFile.substring(0, saveFile.indexOf(&quot;\n&quot;));
saveFile = saveFile.substring(saveFile.lastIndexOf(&quot;\\&quot;) + 1,saveFile.indexOf(&quot;\&quot;&quot;));

int lastIndex = contentType.lastIndexOf(&quot;=&quot;);
String boundary = contentType.substring(lastIndex + 1,contentType.length());
fileName = new String(rootPath +saveFile);

int pos;
pos = file.indexOf(&quot;filename=\&quot;&quot;);
pos = file.indexOf(&quot;\n&quot;, pos) + 1;
pos = file.indexOf(&quot;\n&quot;, pos) + 1;
pos = file.indexOf(&quot;\n&quot;, pos) + 1;

int boundaryLocation = file.indexOf(boundary, pos) - 4;
int startPos = ((file.substring(0, pos)).getBytes()).length;
int endPos = ((file.substring(0, boundaryLocation)).getBytes()).length;

//File fileDir = new File(rootPath);
//if (!fileDir.exists()) {
// fileDir.mkdirs();
//}

fileOut = new FileOutputStream(fileName);
//fileOut.write(dataBytes);
fileOut.write(dataBytes, startPos, (endPos - startPos));
fileOut.flush();
fileOut.close();

} else if (contentType.equals(&quot;application/x- {
fileName = req.getParameter(&quot;quickTipFileName&quot;);
if (fileName.length() < 3) {
doError(req, resp, &quot;You have not entered a filename !&quot;, session);
return;
}

fileName = (rootPath +fileName);
PrintWriter pw = new PrintWriter(new FileOutputStream(fileName));

if (!(new File(rootPath +fileName)).exists()) {
pw.println(&quot;<HTML><BODY>&quot;);
pw.println(req.getParameter(&quot;quickTip&quot;));
pw.println(&quot;</HTML></BODY>&quot;);
} else {
pw.println(req.getParameter(&quot;quickTip&quot;));
}
pw.flush();
pw.close();

} else {
System.out.println(&quot;request not multipart /form - data &quot; + contentType);
doError(req, resp, &quot;request not multipart /form - data &quot; + contentType, session);
}

System.out.println(&quot;!!! File written to : &quot; + fileName);
doSuccess(req, resp, &quot;File written to &quot; + fileName, session);


}
catch (Exception e) {
System.out.println(&quot;Error : &quot; + e.getMessage());
doError(req, resp, &quot;Error : &quot; + e.getMessage(), session);
}
}

public void doSuccess(HttpServletRequest request, HttpServletResponse response, String message, HttpSession session) throws ServletException, IOException {

// Handle successful transactions, and forward control to skbSuccess.jsp
session.setAttribute(&quot;message&quot;, message);
RequestDispatcher rd = getServletContext().getRequestDispatcher(&quot;/skbSuccess.jsp&quot;);
rd.forward(request, response);
}

public void doError(HttpServletRequest request, HttpServletResponse response, String message, HttpSession session) throws ServletException, IOException {
// Handle caught errors, and forward control to skbError.jsp
session.setAttribute(&quot;message&quot;, message);
RequestDispatcher rd = getServletContext().getRequestDispatcher(&quot;/skbError.jsp&quot;);
rd.forward(request, response);
}

}

-----------------------------------
-----------------------------------
---------------------------------
client code ----------------------
-------------------------------------
<HTML>
<BODY>

Choose a file to upload, or enter some text to be added as a 'quick tip' ...
<FORM ACTION=&quot;/components/servlet/UploadServlet&quot; ENCTYPE=&quot;multipart/form-data&quot; METHOD=&quot;post&quot; >
<HR>
<INPUT TYPE=&quot;file&quot; NAME=&quot;fileToUpload&quot;> <BR>

<INPUT TYPE=&quot;submit&quot; VALUE=&quot;UpLoad&quot;>
</FORM>

</BODY>
</HTML>
 
You this code worked perfect without error. But I dont know if the file really upload or just showed me the success page.

You can tell me where in look in Linux directory to see if really file uploaded.

Also can I send the directory rootpath as argument here:
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

String a = req.getParameter("dir");
String rootPath = (String)session.getAttribute(dir);
 
Okay it uploaded.

Can you tell me if there are Multiple Files to uploads what changes I need to make here please...........

HOW TO UPLOAD MULTIPLE FILES ?????? WITH THIS CODE....
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top