Hi,
If you are using any framework like Struts then you can do it very easily, check for example on file upload using struts.
You can also use apaches file upload api, see the following link for more information
http://jakarta.apache.org/commons/fileupload/using.html
or you can use the following code for this purpose
[i]
/**
* @author rakesh
* Created on: 23-11-2006
* Modified on: 27-11-2006
* Modified by: Rakesh
*
*/
package com.fites.b2g.dao;
import java.io.DataInputStream;
import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.LinkedHashMap;
import javax.servlet.ServletContext;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
/**
* This class is used to save [upload] the file selected by the user on the upload page.
* @author rakesh
*
*/
public class FileUploadDAO {
private String savePath, filepath, filename, contentType;
private byte[] b;
byte t;
private LinkedHashMap fields;
public FileUploadDAO(){
}
/**
* This method returns the filename.
* @return String
*/
public String getFilename() {
return filename;
}
/**
* This method will return the absolute path of the file.
* @return String
*/
public String getFilepath() {
return filepath;
}
/**
* This method will set the path to which the file has to be uploaded.
* @param savePath
*/
public void setSavePath(String savePath) {
this.savePath = savePath;
}
/**
* This method will return the content type which is received through request object.
* @return String
*/
public String getContentType() {
return contentType;
}
/**
* This method will return the request parameter value by taking request parameter name.
* @param fieldName name of the request parameter
* @return String value of the request parameter
*/
public String getFieldValue(String fieldName) {
if (fields == null || fieldName == null)
return null;
return (String) fields.get(fieldName);
}
/**
* This method will print the parameters received through request object.
*
*/
public void print(){
Object[] keys = fields.keySet().toArray();
System.out.println("Field Value combinations are : ");
Object[] k = fields.keySet().toArray();
Object[] v = fields.values().toArray();
for(int i=0;i<k.length;i++){
System.out.println(": "+k[i]+" : "+v[i]);
}
}
/**
* This method returns the LinkedHashMap
*/
public LinkedHashMap getHashMap(){
return fields;
}
/**
* This method will remove all special characters.
* @param value string containing special characters.
*/
private String removeSpecialCharacters(String value){
String[] special = {"\'","\"","%","#","@","&","^","!","~","$",",",";" ,":","`"};
if(value == null)
return "";
for(int i=0;i<special.length;i++){
if(value.indexOf(special[i]) > 0)
value = value.replaceAll(special
, "");
}
return value;
}
/**
* This method will set the file name.
* @param s name of the file.
*/
private void setFilename(String s) {
if (s == null)
return;
int pos = s.indexOf("filename=\"");
if (pos != -1) {
filepath = s.substring(pos+10, s.length()-1);
pos = filepath.lastIndexOf("\\");
if (pos != -1)
filename = filepath.substring(pos + 1);
else
filename = filepath;
}
filename = filename.toLowerCase();
filename = this.removeSpecialCharacters(filename);
}
/**
* This method will set the content type of the request object.
* @param s content type.
*/
private void setContentType(String s) {
if (s == null)
return;
int pos = s.indexOf(": ");
if (pos != -1)
contentType = s.substring(pos+2, s.length());
}
/**
* This method will read all the bytes available in the request object and stores them in a variable [b]
* @param request The request object to be read.
*/
public void getByte(HttpServletRequest request){
DataInputStream is;
int i=0;
try {
is=new DataInputStream(request.getInputStream());
b=new byte[request.getContentLength()];
while (true){
try {
t=is.readByte();
b[i++]=t;
}catch(EOFException e){
break;
}
}
is.close();
}catch(IOException e) {}
}
/**
* This method will check the file size and returns true if its more the at least one byte else false.
*/
public boolean checkFileSize(int min){
if(savePath == null || filename == null)
return false;
try{
File file = new File(savePath+"\\"+filename);
FileInputStream finputstream = new FileInputStream(file);
if(finputstream.available() > min){
finputstream.close();
return true;
}else{
finputstream.close();
return false;
}
}catch(Exception e){
e.printStackTrace();
return false;
}
}
/**
* This method will remove the file just been created using this class.
*
*/
public void removeFile(){
if(savePath == null || filename == null)
return;
File user_file = new File(savePath+"\\"+filename);
if(user_file.exists())
user_file.delete();
}
/**
* This method will return the filename with version appended to it.
*
*/
public String getVersionedFile(String value,File directory){
StringBuffer filebuffer = new StringBuffer(value);
filebuffer.replace(value.lastIndexOf('.'), value.lastIndexOf('.')+1, "-v1.");
value = filebuffer.toString();
File file = new File(directory.getAbsolutePath() + "/" + value.toLowerCase());
if(file.exists()){
int ver = 1;
String[] list = directory.list();
for(int k=0;k<list.length;k++){
if(list[k].equals(value)){
int v = Integer.parseInt(""+value.charAt(value.lastIndexOf ('.')-1));
if(ver <= v)
ver = v;
value = value.replaceFirst("-v"+(ver)+".","-v"+(ver+1)+".");
}
}
}
return value;
}
/**
* This method will save the file received through the request object selected by the user in the page.
* @param request request object containing the bytes of the file and the data entered in the page.
* @param context Servlet context object
* @param servlet_name Servlet name.
* @return boolean the status of the upload [ true or false ].
* @throws IOException
*/
public int doUpload(HttpServletRequest request,String filepath,String folder,String userid) throws IOException {
request.setCharacterEncoding("GB2312");
ServletInputStream inputstream = request.getInputStream();
FileOutputStream outputstream = null;
int read_count = 0;
byte[] line = new byte[1280];
try{
File directory = new File(filepath+"/"+folder+"/"+userid);
if(!directory.exists())
directory.mkdirs();
setSavePath(directory.getAbsolutePath());
int readbytes = inputstream.readLine(line, 0, 1280);
if (readbytes < 3)
return -1;
int boundaryLength = readbytes - 2;
String boundary = new String(line, 0, boundaryLength);
fields = new LinkedHashMap();
while (readbytes != -1) {
String newLine = new String(line, 0, readbytes);
if (newLine.startsWith("Content-Disposition: form-data; name=\"")) {
if (newLine.indexOf("filename=\"") != -1) {
setFilename(new String(line, 0, readbytes-2));
if (filename == null){
return -1;
}
readbytes = inputstream.readLine(line, 0, 1280);
setContentType(new String(line, 0, readbytes-2));
readbytes = inputstream.readLine(line, 0, 1280);
readbytes = inputstream.readLine(line, 0, 1280);
newLine = new String(line, 0, readbytes,"ISO8859_1");
try{
if(filename.length() > 0){
this.filename = this.getVersionedFile(filename, directory);
if(request.getContentLength() == 0)
return 0;
outputstream = new FileOutputStream(directory.getAbsolutePath() + "/" + filename.toLowerCase());
while (readbytes != -1 && !newLine.startsWith(boundary)) {
readbytes = inputstream.readLine(line, 0, 1280);
if ((readbytes == boundaryLength+2 || readbytes==boundaryLength+4) && (new String(line, 0, readbytes).startsWith(boundary)))
outputstream.write(newLine.substring(0, newLine.length()-2).getBytes("ISO8859_1"));
else
outputstream.write(newLine.getBytes("ISO8859_1"));
newLine = new String(line, 0, readbytes,"ISO8859_1");
}
outputstream.close();
}
}catch(Exception e){
System.out.println("Error while uploading file content.");
e.printStackTrace();
return -1;
}
}else {
int pos = newLine.indexOf("name=\"");
String fieldName = newLine.substring(pos+6, newLine.length()-3);
readbytes = inputstream.readLine(line, 0, 1280);
readbytes = inputstream.readLine(line, 0, 1280);
newLine = new String(line, 0, readbytes);
StringBuffer fieldValue = new StringBuffer(1280);
while (readbytes != -1 && !newLine.startsWith(boundary)) {
readbytes = inputstream.readLine(line, 0, 1280);
if ((readbytes == boundaryLength+2 || readbytes == boundaryLength+4) && (new String(line, 0, readbytes).startsWith(boundary)))
fieldValue.append(newLine.substring(0, newLine.length()-2));
else
fieldValue.append(newLine);
newLine = new String(line, 0, readbytes);
}
fields.put(fieldName, fieldValue.toString());
}
}
readbytes = inputstream.readLine(line, 0, 1280);
read_count += readbytes;
}
return 1;
}catch(Exception e){
System.out.println("Error while uploading a file.");
e.printStackTrace();
}
return -1;
}
}
You might be interested in the method
doUpload() which actually uploads the file.
Regards,
Rakesh