| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 1034 人关注过本帖
标题:jsp简单的上传下载例子。
只看楼主 加入收藏
QQ785468931
Rank: 2
等 级:论坛游民
帖 子:43
专家分:50
注 册:2011-8-30
结帖率:50%
收藏
已结贴  问题点数:10 回复次数:4 
jsp简单的上传下载例子。
jsp上传下载列子,请不要上网拷贝。写一个出来,可真正部署起来的。利用到数据库保存文件名!
搜索更多相关主题的帖子: jsp 
2012-05-20 16:05
lucky563591
Rank: 11Rank: 11Rank: 11Rank: 11
等 级:小飞侠
威 望:4
帖 子:765
专家分:2103
注 册:2009-11-18
收藏
得分:10 
收到请求就往数据库查找数据名地址再发送。
2012-05-22 09:12
sorryyuan89
Rank: 1
等 级:新手上路
帖 子:2
专家分:0
注 册:2012-6-4
收藏
得分:0 
程序代码:
import import import import import import import 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 编辑 ]
2012-06-04 23:47
jufeng_466
Rank: 1
等 级:新手上路
帖 子:1
专家分:0
注 册:2012-6-6
收藏
得分:0 
有时就不知道该写那些import导入的包。只用那种"*"代替的行吗?

 
2012-06-06 12:23
郭根方
Rank: 1
等 级:新手上路
帖 子:1
专家分:0
注 册:2012-6-8
收藏
得分:0 
当然可以了!
2012-06-08 22:42
快速回复:jsp简单的上传下载例子。
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.021773 second(s), 7 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved