Wrox Programmer Forums
Go Back   Wrox Programmer Forums > Java > Java and JDK > Pro JSP
|
Pro JSP Advanced JSP coding questions. Beginning questions will be redirected to the Beginning JSP forum.
Welcome to the p2p.wrox.com Forums.

You are currently viewing the Pro JSP section of the Wrox Programmer to Programmer discussions. This is a community of software programmers and website developers including Wrox book authors and readers. New member registration was closed in 2019. New posts were shut off and the site was archived into this static format as of October 1, 2020. If you require technical support for a Wrox book please contact http://hub.wiley.com
 
Old May 18th, 2007, 12:11 AM
Registered User
 
Join Date: May 2007
Posts: 1
Thanks: 0
Thanked 0 Times in 0 Posts
Default write the values of textbox to a file

Now what I am doin is I am sending files to inside a folder by setting Form ENCTYPE="multipart/form-data" . Now problem Is that i also want to send some other data like value of textbox , listbox etc , But it is not coming .

Any Help in this context is greeted.


ashi
 
Old May 23rd, 2007, 10:04 AM
Friend of Wrox
 
Join Date: Mar 2007
Posts: 373
Thanks: 0
Thanked 1 Time in 1 Post
Default

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





Similar Threads
Thread Thread Starter Forum Replies Last Post
Popup cannot write int parentwindow textbox greatJ .NET Framework 2.0 0 August 13th, 2007 02:35 AM
hi help me to write javascript to validate textbox karthikc85 XML 1 October 12th, 2006 03:12 AM
How to write value of checked list in textbox gilgalbiblewheel Classic ASP Databases 2 August 10th, 2005 06:08 PM
write values to txt file in server eresina Javascript 7 July 19th, 2005 08:23 AM
write values to txt file in server eresina Javascript How-To 1 July 19th, 2005 05:11 AM





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