当前位置: 代码迷 >> Java Web开发 >> jsp简单的上传下载例子。
  详细解决方案

jsp简单的上传下载例子。

热度:435   发布时间:2012-05-20 16:05:25.0
jsp简单的上传下载例子。
jsp上传下载列子,请不要上网拷贝。写一个出来,可真正部署起来的。利用到数据库保存文件名!
搜索更多相关主题的帖子: jsp  

----------------解决方案--------------------------------------------------------
收到请求就往数据库查找数据名地址再发送。
----------------解决方案--------------------------------------------------------
程序代码:

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
public class UploadBean {
    private InputStream InputStreamState;//输入流
    private HttpServletRequest request;//从JSP页面传入的Request
    private long fileSize;//文件大小
    private String errorMessage = "";//用于保存错误信息
    private Map<String, String> parameter = new HashMap<String, String>();//创建Map集合
    public UploadBean() {
    }


    /**
     * <pre><h1>
     * 解析Form表单
     * form表单的enctype必须设置为:enctype=&quot;multipart/form-data&quot;
     * 此方法为首方法,用于解析form表单中的属性。执行此方法解析表单值后,方可通过 {
@link #getParameter(String)}方法获得表单的参数信息
     * <br>                           
     *
@param contentType
     * 传入内容类型信息。例如:request.getContentType();
     *
@param inputStream
     * 传入请求的输入流。例如:request.getInputStream();
     * </pre>
     
*/
    private void resolverForm() {
        InputStream inputStream = null;
        try {
            inputStream = request.getInputStream();
        } catch (IOException e2) {
            e2.printStackTrace();
        }
        String contentType = request.getContentType();
        if (!isMultipar(contentType) || inputStream.equals(InputStreamState))
            return;
        if (contentType != null && inputStream != null) {
            InputStreamState = inputStream;
            int data;
            StringBuffer datastr = new StringBuffer();
            parameter.clear();
            try {
                while ((data = inputStream.read()) != -1) {
                    datastr.append((char) data);
                    if (fileSize > 0 && datastr.length() > fileSize) {
                        datastr = null;
                        errorMessage = "文件超出大小限制。";
                        parameter.put("error", errorMessage);
                        throw new Exception("文件超出大小限制。");
                    } else
                        parameter.put("error", errorMessage);
                }
                inputStream.close();
                String split = "boundary=";
                String splitStr = "--"
                        + contentType.substring(contentType.indexOf(split)
                                + split.length());
                String[] formFileds = datastr.toString().split(
                        "Content-Disposition: form-data; ");
                for (int i = 0; i < formFileds.length; i++) {
                    int[] index = new int[4];
                    if (!formFileds[i].startsWith(splitStr)) {
                        index[0] = -1;
                        index[1] = formFileds[i].indexOf("\n", index[0]);
                        index[2] = formFileds[i].indexOf("\n", index[1] + 1);
                        index[3] = formFileds[i].indexOf("\n", index[2] + 1);
                        String name = "";
                        for (int lc = 0; lc < index.length - 1; lc++) {
                            String line = formFileds[i].substring(
                                    index[lc] + 1, index[lc + 1]);
                            String[] lineFields = line.split("; ");
                            for (int j = 0; j < lineFields.length; j++) {
                                if (lineFields[j].startsWith("name=")) {
                                    name = lineFields[j].substring(
                                            lineFields[j].indexOf("\"") + 1,
                                            lineFields[j].lastIndexOf("\""));
                                }
                                if (j > 0) {
                                    String arg = name
                                            + "_"
                                            + lineFields[j].substring(0,
                                                    lineFields[j].indexOf("="));
                                    String argContent = lineFields[j]
                                            .substring(lineFields[j]
                                                    .indexOf("\"") + 1,
                                                    lineFields[j]
                                                            .lastIndexOf("\""));
                                    parameter.put(arg, argContent);
                                }
                            }
                            if (line.equals("\r")) {
                                parameter.put(name, formFileds[i].substring(
                                        index[lc + 1] + 1, formFileds[i]
                                                .lastIndexOf(splitStr) - 2));
                                break;
                            }
                        }
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
    /**
     * <pre><h1>
     * 上传文件到服务器
     * </h1>
     *                             
     *     
@param filePath 服务器存放文件的路径
     *                                       
     * </pre>
     
*/
    public boolean uploadToFile(String filearg, String filename, String filePath) {
        if (filename == null || filename.equals("")) {
            filename = System.currentTimeMillis()
                    + new File(getParameter(filearg + "_filename")).getName();
        }
        String contentType = request.getContentType();
        if (!isMultipar(contentType))
            return false;
        resolverForm();
        if (filePath.charAt(filePath.length() - 1) != File.separatorChar)
            filePath += File.separatorChar;
        String submit = getParameter("Submit");
        String file = getParameter(filearg);
        if (submit != null && file != null) {
            try {
                File newfile = new File(new String((filePath + new File(
                        filename).getName()).getBytes("iso-8859-1")));
                newfile.createNewFile();
                FileOutputStream fout = new FileOutputStream(newfile);
                fout.write(file.getBytes("iso-8859-1"));
                fout.close();
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return true;
        }
        return false;
    }

    /**
     * <pre><h1>
     * 获取表单的指定参数
     * </h1>
     *   必须调用 {
@link #resolverForm(String, InputStream)}方法解析form表单以后,才可以调用此方法,否则参数为空。                           
     *   
@param param
     *  参数名称
     *   
@return String 返回类型
     * </pre>
     
*/
    public String getParameter(String param) {
        resolverForm();
        return parameter.get(param);
    }

    /**
     * <pre><h1>
     * 获得form表单的所有参数名称的集合
   
    public Set<String> getParameterNames() {
        resolverForm();
        return parameter.keySet();
    }
    private boolean isMultipar(String contentType) {
        try {
            if (contentType != null
                    && !contentType.startsWith("multipart/form-data")) {
                throw new Exception(
                        "请设置Form表单的enctype属性为:\"multipart/form-data\"");
            } else {
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     
     *         
@param pageContext javax.servlet.jsp.PageContext类型的上下文,
     *         可以直接传入JSP页面中的pageContext内置对象。
   
    public void setRequest(HttpServletRequest request) {
        this.request = request;
    }

    public void setFileSize(long fileSize) {
        this.fileSize = fileSize;
    }
}
数据库操作类:
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;

import lzwBean.LzwUploadBean;

public class FileUploadDao {
    private static FileUploadDao instance = null ;
    public static FileUploadDao getInstance(){
        if (instance == null)
            instance = new FileUploadDao();
        return instance;
    }
    /**
     * 保存文件的方法
     *
@param file 文件字节流串
     *
@return 保存成功返回true,否则返回false
     *
@throws SQLException
     
*/
   
    public boolean  saveFile(String file) throws SQLException{   
        Connection conn = null;
        boolean res = false;
        try{
            conn = DBCon.getConn();//创建数据库连接
            String sql = "insert into tb_file(file) values(?)";//SQL语句
            PreparedStatement stmt = conn.prepareStatement(sql);//创建PreparedStatement对象
            stmt.setBytes(1, file.getBytes("ISO-8859-1"));//将设置文件的原始字节
            int i = stmt.executeUpdate();//执行SQL命令
            if(i>0)
                res = true;
        }catch(Exception ex){
            ex.printStackTrace();
        }finally{
            conn.close();
        }
        return res;
    }
}

其实多看看就会理解,希望能帮助到你 这个只实现了上传功能,有时间再写吧


[ 本帖最后由 sorryyuan89 于 2012-6-4 23:49 编辑 ]
----------------解决方案--------------------------------------------------------
有时就不知道该写那些import导入的包。只用那种"*"代替的行吗?


----------------解决方案--------------------------------------------------------
当然可以了!
----------------解决方案--------------------------------------------------------