Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

how to upload a file  RSS feed

 
saravanan rajendran
Ranch Hand
Posts: 75
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,
please help me last few days i trying lot.I Browsed one file that i want to upload in different path.My "book2" file name must store in this /usr/www/html/uploads/ where to set path in below code Below code where to give the particular file name please help me i new to file concept

when i executing the file in browser showing this error

java.lang.StringIndexOutOfBoundsException: String index out of range: -1

code:

package com.example.servlets;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

public class FileUploadServlet extends HttpServlet{

static final int MAX_SIZE=1024*1024;
String rootPath, successMessage;

public void init(ServletConfig con) throws ServletException{
super.init(con);

rootPath=con.getInitParameter("RootPath");
if (rootPath==null) rootPath="/";

successMessage=con.getInitParameter("SuccessMessage");
if (successMessage==null) successMessage="File Successfully Uploaded!";
}//end init()

public void doPost(HttpServletRequest req, HttpServletResponse res){

DataInputStream in=null;
ServletOutputStream out= null;
FileOutputStream fileOut=null;


try{
res.setContentType("text/plain");
out=res.getOutputStream();

String contentType=req.getContentType();

if (contentType !=null && contentType.indexOf("multipart/form-data")!=-1){
in=new DataInputStream(req.getInputStream());
int formDataLength=req.getContentLength();
if(formDataLength > MAX_SIZE){
out.println("<b>Sorry, File Too Large to Upload, limit=2MB</b>");
out.flush();
return;
}//inner if

byte dataBytes[]=new byte[formDataLength];

int bytesRead=0;
int totalBytesRead=0;
while(totalBytesRead < formDataLength){
bytesRead=in.read(dataBytes, totalBytesRead, formDataLength);
totalBytesRead = totalBytesRead+bytesRead;
}//end while

String file=new String(dataBytes, "ISO8859_1");//store dataBytes in String
dataBytes=null; //release memory

//get Boundary Value i.e. boundary=----------------------------------

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

//get Directory Value

String directory="/var/www/html/uploads/";
if (file.indexOf("name=\"Directory\"") > 0){
directory=file.substring(file.indexOf("name=\"Directory\""));

//remove Carriage Returns
directory=directory.substring(directory.indexOf("\n")+1);
directory=directory.substring(directory.indexOf("\n")+1);

//get Directory
directory=directory.substring(0, directory.indexOf("\n")-1);
if (directory.indexOf("..")>0){
out.println("Security Error: cant upload to that Directory");
return;
}
}//inner if


//get SuccessPage Value
String successPage="book2";
if (file.indexOf("name=\"SuccessPage\"") >0){
successPage=file.substring(file.indexOf("name=\"SuccessPage\""));

//remove Carriage Returns
successPage=successPage.substring(successPage.indexOf("\n")+1);
successPage=successPage.substring(successPage.indexOf("\n")+1);

//get SuccessPage
successPage=successPage.substring(0, successPage.indexOf("\n")-1);
}//inner if


//get OverWrite flag
String overWrite="";
if (file.indexOf("name=\"OverWrite\"") >0){
overWrite=file.substring(file.indexOf("name=\"OverWrite\""));

//remove Carriage Returns
overWrite=overWrite.substring(overWrite.indexOf("\n")+1);
overWrite=overWrite.substring(overWrite.indexOf("\n")+1);

//get SuccessPage
overWrite=overWrite.substring(0, overWrite.indexOf("\n")-1);
}else {overWrite="false";}


//get OverWritePage
String overWritePage="book2";
if (file.indexOf("name=\"OverWritePage\"") >0){
overWritePage=file.substring(file.indexOf("name=\"OverWritePage\""));

//remove Carriage Returns
overWritePage=overWritePage.substring(overWritePage.indexOf("\n")+1);
overWritePage=overWritePage.substring(overWritePage.indexOf("\n")+1);

//get SuccessPage
overWritePage=overWritePage.substring(0, overWritePage.indexOf("\n")-1);
}//inner if


//get FileName of upload file
String saveFile=file.substring(file.indexOf("filename=\"book2\"")+10);
saveFile=saveFile.substring(0, saveFile.indexOf("\n"));
saveFile=saveFile.substring(saveFile.lastIndexOf("\\")+1, saveFile.indexOf("\""));


//remove Boundary Markers

int pos;
pos=file.indexOf("filename=\""); //position of upload file section of request
pos=file.indexOf("\n",pos)+1; //position of content-type line in upload file section
pos=file.indexOf("\n",pos)+1; //position of blank line

//find location of next boundary marker (end of upload file section)
int boundaryLocation=file.indexOf(boundary,pos)-4; //position of upload file section of request


//upload file lies in between pos and boundarylocation
file=file.substring(pos,boundaryLocation);

String fileName=new String(rootPath+directory+saveFile) ;

File checkFile=new File(fileName);
if (checkFile.exists()){
if(! overWrite.toLowerCase().equals("true")){
if(overWrite.equals("")){
out.println("Sorry, File Already Exists!");
}else res.sendRedirect(overWritePage);
return;
}
}

File fileDir=new File(rootPath+directory);
if (! fileDir.exists()){
fileDir.mkdirs();
}
fileOut=new FileOutputStream(fileName);
fileOut.write(file.getBytes("ISO8859_1"),0,file.length());


if (successPage.equals("")){
out.println(successMessage);
out.println("File Written to:"+fileName);
}else res.sendRedirect(successPage);


}//outer if

// if the request is not multipart/form-data
else{
out.println("Request not multipart/form-data.");
}

}catch(Exception exc){
try{
System.out.println(""+exc);
out.println(""+exc);
}catch(Exception excep){}
}finally{
try{
fileOut.close();
in.close();
out.close();
}catch(Exception ex){}

}//end try-catch-finally block
}//end doPost() method
}//end class
 
Ulf Dittmer
Rancher
Posts: 42972
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please UseCodeTags when posting code fo any length. It's unnecessarily hard to read as it is. Please go back and edit your post accordingly.

Also tell us in which line the exception is happening.
 
saravanan rajendran
Ranch Hand
Posts: 75
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi,
thanks for yr replay when i run that code into browser its show below error.please help me

java.lang.StringIndexOutOfBoundsException: String index out of range: -1


code:

String directory="";//here i want to set my path var/www/html/sar/ what format i can give

if (file.indexOf("name=\"Directory\"") > 0){
directory=file.substring(file.indexOf("name=\"Directory\""));

//remove Carriage Returns
directory=directory.substring(directory.indexOf("\n")+1);
directory=directory.substring(directory.indexOf("\n")+1);


//get SuccessPage Value
String successPage="";//here how to set my file name
if (file.indexOf("name=\"SuccessPage\"") >0){
successPage=file.substring(file.indexOf("name=\"SuccessPage\""));

//remove Carriage Returns
successPage=successPage.substring(successPage.indexOf("\n")+1);
successPage=successPage.substring(successPage.indexOf("\n")+1);
 
Maneesh Godbole
Bartender
Posts: 11445
18
Android Eclipse IDE Google Web Toolkit Java Mac Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by saravanan rajendran:


String directory="";//here i want to set my path var/www/html/sar/ what format i can give

;
 
saravanan rajendran
Ranch Hand
Posts: 75
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi,
thanks for yr replay.i want to upload my excel file when i compile below code good its working when i call that program in browser pressing submit button this error display "java.lang.StringIndexOutOfBoundsException: String index out of range: -1"
My problem:
I am not sure whether i giving Dir and file name in Correct place.

please help me


if (contentType !=null && contentType.indexOf("multipart/form-data")!=-1){
in=new DataInputStream(req.getInputStream());
int formDataLength=req.getContentLength();
if(formDataLength > MAX_SIZE){
out.println("<b>Sorry, File Too Large to Upload, limit=2MB</b>");
out.flush();
return;
}//inner if

byte dataBytes[]=new byte[formDataLength];

int bytesRead=0;
int totalBytesRead=0;
while(totalBytesRead < formDataLength){
bytesRead=in.read(dataBytes, totalBytesRead, formDataLength);
totalBytesRead = totalBytesRead+bytesRead;
}//end while

String file=new String(dataBytes, "ISO8859_1");//store dataBytes in String
dataBytes=null; //release memory

//get Boundary Value i.e. boundary=----------------------------------

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

//get Directory Value

String directory="/var/www/html/uploads";//given my dir name
if (file.indexOf("name=\"Directory\"") > 0){
directory=file.substring(file.indexOf("name=\"Directory\""));

//remove Carriage Returns
directory=directory.substring(directory.indexOf("\n")+1);
directory=directory.substring(directory.indexOf("\n")+1);

//get Directory
directory=directory.substring(0, directory.indexOf("\n")-1);
if (directory.indexOf("..")>0){
out.println("Security Error: cant upload to that Directory");
return;
}
}//inner if


//get SuccessPage Value
String successPage="book2";//given my upload file
if (file.indexOf("name=\"SuccessPage\"") >0){
successPage=file.substring(file.indexOf("name=\"SuccessPage\""));

//remove Carriage Returns
successPage=successPage.substring(successPage.indexOf("\n")+1);
successPage=successPage.substring(successPage.indexOf("\n")+1);

//get SuccessPage
successPage=successPage.substring(0, successPage.indexOf("\n")-1);
}//inner if


//get FileName of upload file
String saveFile=file.substring(file.indexOf("filename=book2")+10);
saveFile=saveFile.substring(0, saveFile.indexOf("\n"));
saveFile=saveFile.substring(saveFile.lastIndexOf("\\")+1, saveFile.indexOf("\""));
 
Ben Souther
Sheriff
Posts: 13411
Firefox Browser Redhat VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
saravanan,

You've already been asked to UseCodeTags when posting code fo any length.

I can assure you that, at least one person, has ignored the code in your posts because it's been too hard to read. If you want helpful answers, take the time to make it as easy as possible for people to read your questions.

-Ben
 
Ulf Dittmer
Rancher
Posts: 42972
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Also, we still don't know which line the exception occurs in. You need to track that down first.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!