Uploading a simple File

I can't understand why this such difficult thing, uploading a file via JSP.

I just looking for a simple example to upload a file to server nothing more nothing less.

I've seen to so many complex examples of something very easy to do any other language such as ASP.NET, COLDFUSION, PHP and etc.

Can it be down simple in JSP ?

Can some please help as new to Java and I'm finding this unnecassary challenge.

thanks

[455 byte] By [NUCKZa] at [2007-11-27 8:29:50]
# 1

[nobr]Just to get you started. Dunno where I found this code. Also, this is only to get you started, look into the Apache Commons Upload API. This code only supports files of limited size but works well for very simple/ small apps.

<!-- upload.jsp -->

<%@ page import="java.io.*" %>

<%

//String path = application.getRealPath("/") + "ADP\\";

//out.println(path);

//String pathSeparator = File.separator; // will return either "\" or "/", depends on OS

//out.println(pathSeparator);

//String myFilePath = "some dir" + pathSeparator + "myfile.txt";

//String fullPath = path + myFilePath;

String contentType = request.getContentType();

System.out.println("Content type is :: " +contentType);

if ((contentType != null) && (contentType.indexOf("multipart/form-data") >= 0)) {

DataInputStream in = new DataInputStream(request.getInputStream());

int formDataLength = request.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("filename=\"") + 10);

//out.print("FileName:" + saveFile.toString());

saveFile = saveFile.substring(0, saveFile.indexOf("\n"));

//out.print("FileName:" + saveFile.toString());

saveFile = saveFile.substring(saveFile.lastIndexOf("\\") + 1,saveFile.indexOf("\""));

//out.print("FileName:" + saveFile.toString());

//out.print(dataBytes);

int lastIndex = contentType.lastIndexOf("=");

String boundary = contentType.substring(lastIndex + 1,contentType.length());

//out.println(boundary);

int pos;

pos = file.indexOf("filename=\"");

pos = file.indexOf("\n", pos) + 1;

pos = file.indexOf("\n", pos) + 1;

pos = file.indexOf("\n", 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;

//saveFile = path + saveFile;

FileOutputStream fileOut = new FileOutputStream(saveFile);

//fileOut.write(dataBytes);

fileOut.write(dataBytes, startPos, (endPos - startPos));

fileOut.flush();

fileOut.close();

//boolean isDeleted = new File(saveFile).delete();

//out.println("isDeleted? : " + isDeleted );

//out.println("File saved as " +saveFile);

}

%>

You need to create a form for file selection and set the appropriate encoding:

<form action="upload.jsp" method="POST" enctype="multipart/form-data">

<!-- enctype="multipart/form-data" -->

<input type="file" name="theFile"><br>

<input type="submit">

</form>

[/nobr]

nogoodatcodinga at 2007-7-12 20:20:14 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...
# 2
hi... where i have to spcify the destination dir path..can you please help..thanks
ravi-kumar-123a at 2007-7-12 20:20:14 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...
# 3

This statement creates the file of the same name as that which was uploaded:

FileOutputStream fileOut = new FileOutputStream(saveFile);

This indicates that saveFile contains the name of the file. If you just give the filename, the file will get uploaded into Windows/system32 for a Windows machine since that is the default working directory.

What you can do is append the saveFile string to your path and hence, set the directory. The code is there in the sample, only commented out. You can use this:

String path = application.getRealPath("/") + "ADP\\"; //will only work for apps that are not deployed as .wars

//also the directory ADP\ is hardcoded with the path separator for Windows machines, ideally, you should use:

//String pathSeparator = File.separator; // will return either "\" or "/", depends on OS

//to get the path separator and then append that.

saveFile = path + saveFile;

nogoodatcodinga at 2007-7-12 20:20:14 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...
# 4
THANKX A LOT GUYS................ITS WORKING FINE....
ravi-kumar-123a at 2007-7-12 20:20:14 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...
# 5

Thanks for the post and code still that's my problem with java it requires to much code. I ended up deciding to figure out how this logically works. So I code my own solution to very simple problem.

The drawback is a limited file size and the stupid way of copying a file but the browse file isn't object in java.

// this finds the server path

String path = this.getServletContext().getRealPath("");

// HTML Browse id="file" gets the uploaded path

String uploadFilePath = request.getParameter("file");

File fromFile = new File(uploadFilePath);

// where I'm going to save the file using the same file name

File toFile = new File(path+"//"+fromFile.getName());

// MAX of 20MB Files

byte buffer[] = new byte[20 * 1024];

FileInputStream from = new FileInputStream(fromFile);

FileOutputStream to = new FileOutputStream(toFile);

int bytesRead;

//this loop is copying and writing the btyes of file to a specified new location

while ((bytesRead = from.read(buffer)) != -1)

to.write(buffer, 0, bytesRead); // write

// to unlock the files.

// if u don't do this they'll held by the application and be read-only also this will cause some problems.

to.close();

from.close();

Hope you'll enjoy your java experience cause I'm not, this is definitley a patched together language. java is very powerfully but it's shocking on the web. it takes way 2 long 4 real work deadlines unless you create or have a large library of predefined code.

NUCKZa at 2007-7-12 20:20:14 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...