Wrox Programmer Forums

Need to download code?

View our list of code downloads.

Go Back   Wrox Programmer Forums > Java > Java and JDK > JSP Basics
Password Reminder
Register
| FAQ | Members List | Search | Today's Posts | Mark Forums Read
JSP Basics Beginning-level questions on JSP. More advanced coders should post to Pro JSP.
Welcome to the p2p.wrox.com Forums.

You are currently viewing the JSP Basics section of the Wrox Programmer to Programmer discussions. This is a community of tens of thousands of software programmers and website developers including Wrox book authors and readers. As a guest, you can read any forum posting. By joining today you can post your own programming questions, respond to other developers’ questions, and eliminate the ads that are displayed to guests. Registration is fast, simple and absolutely free .
DRM-free e-books 300x50
Reply
 
Thread Tools Search this Thread Display Modes
  #1 (permalink)  
Old April 4th, 2007, 01:02 AM
Registered User
 
Join Date: Dec 2006
Location: Cuddalore, Tamilnadu, India.
Posts: 6
Thanks: 0
Thanked 0 Times in 0 Posts
Send a message via Yahoo to krishnamoorthymca
Default Problem in upload photo to domain server

hi frnds,
i had a problem with upload the photo to the server. i am the following code to upload the photo to database from the client system

        String filename=request.getParameter("mainphoto");
        File filein = new File(filename);
    int filelength = (int) filein.length();
    InputStream streamedfile = new FileInputStream(filein);
    ps.setBinaryStream(1, streamedfile, filelength);
    ps.executeUpdate();
    ps.close();
    streamedfile.close();
this code is working properly when i am work wit my local system as a server(tomcat) but after launch this project to the domain, i am facing the problem.


Krishnamoorthy.S
Reply With Quote
  #2 (permalink)  
Old April 10th, 2007, 07:31 AM
Friend of Wrox
 
Join Date: Mar 2007
Location: Hyderabad, A.P., India.
Posts: 373
Thanks: 0
Thanked 1 Time in 1 Post
Default

Hi,

the code snipet you've provided is not complete, i cann't figure out the logic you are using for uploading the image.
To upload a file to the server
 1. you've to use the enctype attribute in the form tag.
 2. You cann't use request.getParameter() method to get the parameters or file name or file content.
 3. you've to recieve all the form data as byte streams and create the file stream use that stream to insert the image data into the database.

Regards,
Rakesh
Reply With Quote
  #3 (permalink)  
Old April 10th, 2007, 11:54 PM
Registered User
 
Join Date: Dec 2006
Location: Cuddalore, Tamilnadu, India.
Posts: 6
Thanks: 0
Thanked 0 Times in 0 Posts
Send a message via Yahoo to krishnamoorthymca
Default

hi rakesh, first i like to say thanks for ur valuable effort..

<form method="get" name="uploadphoto" action="uploadserver.jsp" enctype="multipart/form-data">
<table border="0" width="90%" id="table2">
<tr>
<td class=txt1_bold height="25" width="96%" colspan=2>Upload Photo</td>
</tr>
<tr>
<td width="64%">
    <INPUT class=submitbutton style="WIDTH: 224; height:21" type="file" name="mainphoto" accept="image/gif" accept="image/jpeg">
</td>
<td width="34%"><INPUT class=submitbutton style="WIDTH: 110px;" type=submit value="Upload Photo" name=submit onClick="return validate_photo(uploadphoto)">
</td>
</tr>
</table>

contact me: krishnamoorthymca@rediffmail.com
mobile: 9942939383


Krishnamoorthy.S
Reply With Quote
  #4 (permalink)  
Old April 20th, 2007, 12:46 AM
Friend of Wrox
 
Join Date: Mar 2007
Location: Hyderabad, A.P., India.
Posts: 373
Thanks: 0
Thanked 1 Time in 1 Post
Default

hi,

The code you've posted uses some third part api to upload the image. I couldn't able to go through it right now.
But i've a file upload component, which you can use and re implement according to your requirements. see the following code

/**
 * @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[i], "");
        }
        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;
    }
}


Regards,
Rakesh
Reply With Quote
  #5 (permalink)  
Old April 20th, 2007, 12:49 AM
Friend of Wrox
 
Join Date: Mar 2007
Location: Hyderabad, A.P., India.
Posts: 373
Thanks: 0
Thanked 1 Time in 1 Post
Default

Hi,
forgot to mention that you might be interested to look into the method doUpload(). That is where file gets uploaded.

Regards,
Rakesh
Reply With Quote
Reply


Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off
Trackbacks are Off
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Image Upload to different domain Ivision ASP.NET 2.0 Professional 1 August 3rd, 2008 12:45 PM
Problem in upload photo to domain server krishnamoorthymca Linux 0 April 4th, 2007 03:48 AM
Problem in upload photo to domain server krishnamoorthymca J2EE 0 April 4th, 2007 01:03 AM
how to make browser....and upload photo.. jhanny007 PHP How-To 2 March 29th, 2007 02:26 PM
Display 'no photo' in a JSP when photo is not pres Inderjeet Pro JSP 0 April 21st, 2006 05:35 AM



All times are GMT -4. The time now is 10:20 AM.


Powered by vBulletin®
Copyright ©2000 - 2020, Jelsoft Enterprises Ltd.
© 2013 John Wiley & Sons, Inc.