• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

File Upload Problem(Database and Dirctory)

 
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Dear All,
I using oreilly's MultipartRequest for file upload.
I am reading the file from Servlet stream first and inserting it into DB ,
now I want this file to copy into AppServer's directory also , but
I m getting error "Corrupt form data: premature ending".
It seems my same stream is being used for Upload to directory and writing in DB.
If I do vice versa I get "Null pointer exception".
How can do both the things together.
Any clue will be helpful.
Thanks in advance.
Regards,
Dushyant Bhardwaj
 
Dushyant Bhardwaj
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Can anybody some light on it.
Thanks in advance.
Regards,
Dushyant Bhardwaj
 
Ranch Hand
Posts: 572
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
send the code where are you doing all this.
 
Dushyant Bhardwaj
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Kindly bear with the length of the code---
public class PAYImageUpload extends HttpServlet {
Connection con =null;
String values[] = null;
String fileBoundary = null;
PAYFCInputhandle in = null;
PrintWriter out = null;
PAYTFReportEntity repEntity = null;
public javax.servlet.ServletRequest request;
public void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
request=req;
res.setContentType("text/html");
out = res.getWriter();
insertImage(req,res);
}
/**
* This method inserts an image into database.
* Creation date: (8/10/2002 2:35:24 PM)
*/
public void insertImage(javax.servlet.http.HttpServletRequest req,javax.servlet.http.HttpServletResponse res) {
boolean signError = true;
String line = "";
String query = "";
String custCode = "";
String imgType = "";
String imgName = "";
String tmFlag = "";
String signCode = "";
String fName = "";
String txnSrc = "";
String actFlag = "";
String mcFlag = "";
String makerCode = "";
String makerDate = "";
String checkerCode = "";
String checkerDate = "";
String remarks = "";
String businessDate = "";
String message = "";
String exists = "N";
String varCount = "";
String errCode = null;
String tableName = "";
int custId = 0;
int makerId = 0;
int checkerId = 0;
int logBrId = 0;
int txnCtryId = 0;
int wrkBrId = 0;
int signId = 0;
int imgId = 0;
int langId = 0;
int docId = 0;
int pos = 0;
int sID = 0;
int retValint = 0;
int varNo = 0;
int rowCount = 0;
int rowCountSP= 0;
int rowCountUP= 0;
int rowCountDel=0;
int errId = 0;
String imgArray[] = new String[10];
String logoArray[] = new String[10];
java.sql.Blob blb = null;
oracle.sql.BLOB typedBlob = null;
ResultSet rs = null;
StringBuffer varQuery = new StringBuffer();
repEntity = new PAYTFReportEntity();
try{
//Get connection object
con=repEntity.getConnection();
String contentType = req.getContentType();
if ((contentType ==null)||(!contentType.toLowerCase().startsWith("multipart/form-data")))
throw new IOException("Posted content Type is not multipart/form-data");
/* get content length */
int length = req.getContentLength();
byte[] retVal = new byte[length];
/* get index of the boundary */
int index = contentType.lastIndexOf("boundary=");
/* get the boundary */
String boundary = contentType.substring(index+9);
fileBoundary = boundary;
/* Input Handle */
in = new PAYFCInputhandle(req.getInputStream(),boundary ,length);
line=in.readLine();
line=in.readLine();
checkContentDispInfo(line);
line=in.readLine();
line=in.readLine();
if(line!=null && !line.equals(""))
custCode=line;
else
custCode ="";
line=in.readLine();
line=in.readLine();
checkContentDispInfo(line);
line=in.readLine();
line=in.readLine();
line=in.readLine();
line=in.readLine();
checkContentDispInfo(line);
line=in.readLine();
line=in.readLine();
line=in.readLine();
line=in.readLine();
checkContentDispInfo(line);
line=in.readLine();
line=in.readLine();
imgName=line;
line=in.readLine();
line=in.readLine();
checkContentDispInfo(line);
line=in.readLine();
line=in.readLine();
varCount=line;
if(varCount!=null && !varCount.equalsIgnoreCase(""))
varNo=Integer.parseInt(varCount);
varNo=varNo+9;
values = new String[varNo];
for(int i=0;i<varNo;i++){
line=in.readLine();
line=in.readLine();
checkContentDispInfo(line);
line=in.readLine();
line=in.readLine();
// Array for holding values
values[i]=line;
}
line=in.readLine();
line=in.readLine();
checkContentDispInfo(line);
line=in.readLine();
line=in.readLine();
if(values[pos]!=null && !values[pos].equals(""))
{
custId = Integer.parseInt(values[pos++]);
}
else{
pos++;
}
txnSrc = values[pos++];
actFlag = values[pos++];
mcFlag = values[pos++];
if(values[pos]!=null && !values[pos].equalsIgnoreCase("")){
langId = Integer.parseInt(values[pos++]);
}
else{
pos++;
}
makerDate=values[pos++];
imgType = values[pos++];
if(imgType.equalsIgnoreCase("S"))
signCode = values[pos++];
tmFlag = values[pos++];
if(imgType.equalsIgnoreCase("S") && values[pos]!=null && !values[pos].equalsIgnoreCase("")){
signId = Integer.parseInt(values[pos++]);
}
else if((imgType.equalsIgnoreCase("L") || imgType.equalsIgnoreCase("G")) && values[pos]!=null && !values[pos].equalsIgnoreCase("")){
imgId = Integer.parseInt(values[pos++]);
}
fName = values[pos++];
if(values[pos]!=null && !values[pos].equalsIgnoreCase("")){
makerId = Integer.parseInt(values[pos++]);
}
else{
pos++;
}
makerCode = values[pos++];
if(values[pos]!=null && !values[pos].equalsIgnoreCase("")){
logBrId = Integer.parseInt(values[pos++]);
}
else{
pos++;
}
if(values[pos]!=null && !values[pos].equalsIgnoreCase("")){
txnCtryId = Integer.parseInt(values[pos++]);
}
else{
pos++;
}
if(values[pos]!=null && !values[pos].equalsIgnoreCase("")){
wrkBrId = Integer.parseInt(values[pos++]);
}
else{
pos++;
}
businessDate = values[pos++];
checkerId=makerId;
checkerCode=makerCode;
checkerDate=makerDate;
// Get DOC_ID from sequence
rs=repEntity.executeQuery("SELECT CPAY_DOCUMENT_REPOSITORY_SEQ.NEXTVAL FROM DUAL");
while(rs.next()){
docId=Integer.parseInt(rs.getString(1));
}
rs=null;
// create a blob entry in the table
varQuery.append("INSERT INTO CPAY_DOCUMENT_REPOSITORY(DOC_ID,IMAGE_TYPE,CUSTOMER_ID,CUSTOMER_CODE,SIGNATORY_ID,\n");
varQuery.append("SIGNATORY_CODE,FILE_NAME,IMAGE_NAME,IMAGE,ACTIVE_FLAG,MAKERID,MC_FLAG,MAKER_CODE,MAKERDATE, \n");
varQuery.append("CHECKERID,CHECKER_CODE,CHECKERDATE,LOG_BR_ID,TXN_CTRY_ID,WORK_BR_ID,BUS_DATE,TXN_SRC,LANG_ID, \n");
varQuery.append("REMARKS) VALUES( \n");
varQuery.append(docId);
varQuery.append(",'");
varQuery.append(imgType);
varQuery.append("',");
varQuery.append(custId);
varQuery.append(",'");
varQuery.append(custCode);
varQuery.append("',");
varQuery.append(signId);
varQuery.append(",'");
varQuery.append(signCode);
varQuery.append("','");
varQuery.append(fName);
varQuery.append("','");
varQuery.append(imgName);
varQuery.append("',EMPTY_BLOB(),'");
varQuery.append(actFlag);
varQuery.append("',");
varQuery.append(makerId);
varQuery.append(",'");
varQuery.append(mcFlag);
varQuery.append("','");
varQuery.append(makerCode);
varQuery.append("',TO_DATE('");
varQuery.append(makerDate);
varQuery.append("','DD/MM/RRRR'),");
varQuery.append(checkerId);
varQuery.append(",'");
varQuery.append(checkerCode);
varQuery.append("',TO_DATE('");
varQuery.append(checkerDate);
varQuery.append("','DD/MM/RRRR'),");
varQuery.append(logBrId);
varQuery.append(",");
varQuery.append(txnCtryId);
varQuery.append(",");
varQuery.append(wrkBrId);
varQuery.append(",TO_DATE('");
varQuery.append(businessDate);
varQuery.append("','DD/MM/RRRR'),'");
varQuery.append(txnSrc);
varQuery.append("',");
varQuery.append(langId);
varQuery.append(",'");
varQuery.append(remarks);
varQuery.append("')");
query=varQuery.toString();
PAYTFFileDebug.trace("insertImage() query"+query.toString(),PAYTFFileDebug.LEVEL_5);
rowCount=repEntity.executeUpdate(query);
/* To insert Blob into table */
insertBlob(docId);
if(imgType.equalsIgnoreCase("S"))
{
query="UPDATE CPAY_SIGNATORY_STORE_TMP SET DOC_ID="+docId+",MAKERID="+makerId+",MAKER_CODE='"+makerCode+"',MAKERDATE=TO_DATE('"+makerDate+"','DD/MM/RRRR') WHERE SIGNATORY_ID="+signId;
rowCountUP=repEntity.executeUpdate(query);
}
if(imgType.equalsIgnoreCase("L") || imgType.equalsIgnoreCase("G"))
{
query="UPDATE CPAY_CUST_LOGOGIF_TMP SET DOC_ID="+docId+",MAKERID="+makerId+",MAKER_CODE='"+makerCode+"',MAKERDATE=TO_DATE('"+makerDate+"','DD/MM/RRRR') WHERE IMG_ID="+imgId;
rowCountUP=repEntity.executeUpdate(query);
}
String uploadDir = "D:/IMGUpload";//Hardcoding for testing
MultipartRequest multi = new MultipartRequest(request,uploadDir, 15 * 1024 * 1024);
message="Image uploaded successfully.";
if(rowCount>0 && rowCountUP>0)
repEntity.closeConnection(true);
else
repEntity.closeConnection(false);
}
catch(Exception argEx){
message="Image not upload due to error : "+argEx.toString();
PAYTFFileDebug.trace("Exception in PAYImageUpload's insertImage() "+argEx.toString(),PAYTFFileDebug.LEVEL_5);
try{
repEntity.closeConnection(false);
}
catch(Exception ex){}
}
out.println(msg);//sucess or err msg
}
public void insertBlob(int docId) throws Exception{
java.sql.Blob blb = null;
oracle.sql.BLOB typedBlob = null;
byte []tempBuffer = null;
int myCurrentByte = 0;
try{
/*
Conn.setAutoCommit (false);
This is absolutely necessary in this case and any case where you are doing
a select for update. Not doing this will result in a ORA-1002
*/
con.setAutoCommit (false);
ResultSet rs=null;
//Statement stmt=con.createStatement();
String query = "SELECT * FROM CPAY_DOCUMENT_REPOSITORY WHERE DOC_ID="+docId +" FOR UPDATE";
rs = repEntity.executeQuery(query);
rs.next();
blb = rs.getBlob(9);
if(blb instanceof oracle.sql.BLOB)
typedBlob=(oracle.sql.BLOB)blb;
// Open a stream to write the BLOB data
OutputStream blbOpStream = typedBlob.getBinaryOutputStream();
// Open a strem to read data
ByteArrayOutputStream objByteArrayOutputStream = new ByteArrayOutputStream();
sendDataBASFinal(objByteArrayOutputStream);

//Populate buffer with data from stream
tempBuffer = objByteArrayOutputStream.toByteArray();
myCurrentByte=objByteArrayOutputStream.size();
// Write to BLOB
blbOpStream.write(tempBuffer,0,myCurrentByte);
//Flush and close stream
blbOpStream.flush();
blbOpStream.close();
rs=null;

}catch(Exception argEx){
PAYTFFileDebug.trace("Exception in PAYImageUpload's insertBlob() : "+argEx.toString(),PAYTFFileDebug.LEVEL_5);
throw new Exception(argEx.getMessage());
}
}
public void sendDataBASFinal(OutputStream paramOpstream) throws Exception
{
ByteArrayOutputStream myBaos = new ByteArrayOutputStream();
BufferedOutputStream bfos = new BufferedOutputStream(paramOpstream,10240);
int myCurrentByte = 0;
int mysize = 0;
int offset = 0;
int length = 10240;
int left = 0;
int flag = 0;
int totaltransfered = 0;
int end_position = 0;
int endOfFile = 0;
byte []bytebuffer = null;
byte []tempbuffer= new byte[10*1024];
String line = null;
long abc =0;
try{
do
{
myCurrentByte = in.in.read(tempbuffer);
mysize=mysize+myCurrentByte;
if(myCurrentByte != -1)
{
if((myCurrentByte > fileBoundary.length()) || (myCurrentByte == fileBoundary.length()))
{
line = new String(tempbuffer,0,myCurrentByte);
end_position = checkBoundary(line);
if(end_position != -1)
{
if(end_position > 2)
{
end_position = end_position - 2;
myBaos.write(line.substring(0,end_position).getBytes());
myBaos.flush();
}
else
{
myBaos.write(line.substring(end_position,myCurrentByte).getBytes());
}
endOfFile = 1;
}
else
{
myBaos.write(tempbuffer,0,myCurrentByte);
myBaos.flush();
}
}
else
{
myBaos.write(tempbuffer,0,myCurrentByte);
myBaos.flush();
}
}
if((myBaos.size() == 15360) || (myBaos.size() > 15360))
{
totaltransfered = totaltransfered + myBaos.size();
myBaos.writeTo(bfos);
bfos.flush();
//clearing stuff for further write
myBaos.reset();
}
}while((myCurrentByte != -1) && (endOfFile == 0));
mysize = myBaos.size();
myBaos.writeTo(bfos);
bfos.flush();
myBaos.close();
myBaos.reset();
paramOpstream.close();
bfos.flush();
bfos.close();
}catch(Exception argEx){
PAYTFFileDebug.trace("Exception in PAYImageUpload's sendDataBASFinal() : "+argEx.toString(),PAYTFFileDebug.LEVEL_5);
throw new Exception(argEx.getMessage());
}
}
public int checkBoundary(String line) {
boolean returnFlag =false;
String tempFileNextline = null;
String tempFileNextlineBegin = null;
String tempFileNextlineBeginEnd = null;
String tempFileNextlineBeginEndBndry = null;
int start_pos = 0;
int end_pos = 0;
try{
if(true){
start_pos = line.indexOf(fileBoundary);
}
else{
if((line.length() > fileBoundary.length()+2) || (line.length() == fileBoundary.length()+2)){
start_pos = line.length()-fileBoundary.length()-2;
end_pos = start_pos + fileBoundary.length();
tempFileNextlineBeginEndBndry = line.substring(start_pos-2,end_pos);
if((tempFileNextlineBeginEndBndry.endsWith(fileBoundary)) || (tempFileNextlineBeginEndBndry.startsWith(fileBoundary)) )
{
////FileDebugger
}
}
else{
if(line.substring(0,2) == "--"){
tempFileNextlineBeginEnd = line.substring(2,line.length()-2);
tempFileNextlineBegin = line.substring(0,line.length()-2);
tempFileNextline = line.substring(2,line.length());
}
else
tempFileNextlineBeginEnd = line;
if((tempFileNextlineBeginEnd.endsWith(fileBoundary)) || (tempFileNextlineBeginEnd.startsWith(fileBoundary)))
{
start_pos = 3;
}
else if((tempFileNextlineBegin.endsWith(fileBoundary)) || (tempFileNextlineBegin.startsWith(fileBoundary)))
{
start_pos = 0;
}
else if((tempFileNextlineBegin.endsWith(fileBoundary)) || (tempFileNextlineBegin.startsWith(fileBoundary)))
{
start_pos = 3;
}
}
}
}catch(Exception argEx){
}
return start_pos;
}
public void checkContentDispInfo(String line) throws java.io.IOException {
try{
line = line.toLowerCase();
int first = line.indexOf("content-disposition: ");
int last = line.indexOf(";");
if(first == -1 || last == -1)
throw new IOException("Content disposition corrupt : " + line);

String disp = line.substring(first+21,last);
if (!disp.equals("form-data"))
throw new IOException("Content disposition corrupt : " + disp);
/* get field name */
first = line.indexOf("name=\"",last);
last = line.indexOf("\"", first+7);
String name = line.substring(first+6 ,last);
}catch(Exception argEx){
}
}
}
Thanks & Regds
Dushyant Bhardwaj
 
Ali Gohar
Ranch Hand
Posts: 572
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

I am reading the file from Servlet stream first and inserting it into DB ,
now I want this file to copy into AppServer's directory also , but
I m getting error "Corrupt form data: premature ending".
It seems my same stream is being used for Upload to directory and writing in DB.
If I do vice versa I get "Null pointer exception".


I think its because you read the bytes from the Stream and insert it into the DB then the Stream is empty and you again try to read the stream to store the image in directory.
Read the Stream once and get all the bytes then insert those bytes to the DB and also write those bytes in the Upload directory with the image file name. So the File will be saved in the directory.
May be this will help.
 
Dushyant Bhardwaj
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Dear Ali,
That is exactly the problem that how to preserv my original
Stream or re-create the stream so that my second operation
can be performed from the same stream.
For fileupload I am using Oreilly's MultipartRequest which reads
from Servlet Stream.
Any clue will be helpful.
Thanks & Regards,
Dushyant Bhardwaj
 
it's a teeny, tiny, wafer thin ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic