jsp上传文件到数据库mysql_jsp上传文件到数据库和从数据库下载文件

这篇博客介绍了如何使用jsp将文件上传到MySQL数据库,并实现从数据库下载文件。文章提到了使用commons-fileupload和commons-io库,通过Java代码展示了连接数据库、插入文件信息到数据库、读取文件流并保存到数据库的步骤。同时,还提供了下载文件的代码,包括设置Content-Disposition和Content-Type头,以及从数据库获取文件内容并输出到响应流。
摘要由CSDN通过智能技术生成

用了commons-fileupload-1.2.jar和commons-io-1.3.2.jar这两个包。

save.jsp

保存上传文件

文件列表:

文件名大小

// 连接字

String SQL_CON_DRIVER = "com.mysql.jdbc.Driver";

String SQL_CON_USERNAME = "root";

String SQL_CON_PASSWORD = "ddd";

String SQL_CON_STRING = "jdbc:mysql://localhost/ddd?useUniCode=true&characterEncoding=utf-8";

// 连接驱动

try{

Class.forName(SQL_CON_DRIVER).newInstance();

}

catch(ClassNotFoundException e){

out.print(e);

}

// 连接

Connection conn = DriverManager.getConnection(SQL_CON_STRING,SQL_CON_USERNAME,SQL_CON_PASSWORD);

ResultSet rs = null;

PreparedStatement pstmt=conn.prepareStatement("insert into require_file(file_name,file_content) values(?,?)");

%>

int errorType_int =1;

String msg = "";

DiskFileUpload fu = new DiskFileUpload();

// 设置允许用户上传文件大小,单位:字节

//fu.setSizeMax(2*1024*1024);//2m

// 设置最多只允许在内存中存储的数据,单位:字节

fu.setSizeThreshold(4096);

// 设置一旦文件大小超过getSizeThreshold()的值时数据存放在硬盘的目录

//(临时存放目录,文件上传完毕后有办法清除它吗?)

// fu.setRepositoryPath("D://TEMP");

//开始读取上传信息

List fileItems = fu.parseRequest(request);

// 依次处理每个上传的文件

Iterator iter = fileItems.iterator();

//正则匹配,过滤路径取文件名

String regExp=".+(.+)$";

//过滤掉的文件类型

String[] errorType={"exe","com","cgi","asp","jsp"};

Pattern p = Pattern.compile(regExp);

while (iter.hasNext())

{

FileItem item = (FileItem) iter.next();

//忽略其他不是文件域的所有表单信息

if (!item.isFormField())

{

String name = item.getName();//获取上传的文件名

long size = item.getSize();//获取上传的文件大小(字节为单位)

if(size>=2*1024*1024){

out.println("文件大小超过2M");

break;

}

if((name==null||name.equals("")) && size==0||size>=2*1024*1024)

{

continue;//跳到while检查条件

}

Matcher m = p.matcher(name);

boolean result = m.find();

//以下为文件名处理。

if (result){

for (int temp=0;temp

if (m.group(1).endsWith(errorType[temp])){

out.println(name+": wrong type");

errorType_int=0;

//throw new IOException(name+": wrong type");

}

}

// if(errorType_int!=0)

try{

//PreparedStatement pstmt=conn.prepareStatement("insert into require_file(file_name,file_size,file_version,file_uploader,file_alter,file_content) values(?,?)");

if(errorType_int!=0){

int byteread=0;

InputStream inStream=item.getInputStream(); //读取输入流,也就是上传的文件内容

pstmt.setString(1,m.group(1));

pstmt.setBinaryStream(2,inStream,(int)size);

pstmt.executeUpdate();

inStream.close();

out.println(name+"  "+size+"
");

errorType_int=1;

}

/*

//上传到目录

if(errorType_int!=0){

//item.write(new File("d://" + m.group(1)));

//out.print(name+"  "+size+"
");

//获取文件名字符串的长度

int end = name.length();

//返回在此字符串中最右边出现的指定子字符串的索引。

int begin = name.lastIndexOf("//");

File savedFile = new File(fu.getRepositoryPath(), name.substring(begin+1,end));

item.write(savedFile);

out.println("

");

out.println("

" + name + "");

out.println("

" + size + "");

errorType_int=1;

}

*/

}

catch(Exception e){

// 回滚事务,如不需要可去掉

try{conn.rollback ();} catch (java.sql.SQLException ignore){}

out.println(e);

}finally{}

}

else{

throw new IOException("fail to upload");

}

}

}

if (pstmt != null) {

try { pstmt.close(); } catch (java.sql.SQLException ignore) {}

}

if (conn != null) {

try { conn.close(); } catch (java.sql.SQLException ignore) {}

}

%>

返回上传页面

down.jsp

Class.forName("com.mysql.jdbc.Driver").newInstance();

String url = "jdbc:mysql://localhost/ddd?user=root&password=&useUnicode=true&characterEncoding=utf-8";

//其中mysql为你数据库的名字,user为你连接数据库的用户,password为你连接数据库用户的密码,可自己改

Connection conn = DriverManager.getConnection(url, "root", "ddd");

ResultSet rs = null;

int down_id=0;

String down_id_string = request.getParameter("down_id");

if(down_id_string==null){

out.println("没有你要下载的文件");

}

else{

down_id=Integer.parseInt(down_id_string); //获得下载的文件id

}

String sql = "select file_name,file_content  from require_file  where id="+down_id+"";

try {

stmt = conn.createStatement();

rs = stmt.executeQuery(sql);

} catch (SQLException e) {

}

try {

if (rs.next()) {

response.setHeader("Content-Disposition","attachment;filename="+URLEncoder.encode(rs.getString("file_name"),"UTF-8"));

response.setHeader("Connection",  "close");

response.setHeader("Content-Type",  "application/octet-stream");

ServletOutputStream sout = response.getOutputStream();

InputStream  in = rs.getBinaryStream("file_content");

byte b[] = new byte[1024*8];

for(int i=in.read(b);i!=-1;)

{

sout.write(b);

i=in.read(b);

}

sout.flush();

sout.close();

in.close();

}

} catch (Exception e) {

System.out.println(e);

}finally

{

if(rs != null)

{

rs.close();

}

if(stmt != null)

{

stmt.close();

}

if(conn != null)

{

conn.close();

}

}

%>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值