web文件上传与下载综合案例(数据库)

        之前发布了有关于文件上传和下载的一些知识,今天我结合数据库使用SpringMvc技术做了一个web版本的比较使用的上传与下载案例。步骤如下:

一、准备环境

(1)创建一个web工程

(2)准备工程需要的jar包(在这里我多导入了一些,防止因为缺少jar包,出现错误)


(3)编写application.xml和springmvc.xml,代码如下:

application.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop" 
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans 
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd 
http://www.springframework.org/schema/mvc 
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd 
http://www.springframework.org/schema/context 
http://www.springframework.org/schema/context/spring-context-3.2.xsd 
http://www.springframework.org/schema/aop 
http://www.springframework.org/schema/aop/spring-aop-3.2.xsd 
http://www.springframework.org/schema/tx 
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd ">

<!-- 配置数据源 -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/webuploadanddown?useUnicode=true&amp;characterEncoding=utf8"/>
<property name="username" value="root"/>
<property name="password" value="410923"/>
</bean>

<!-- 配置SqlSessionFactory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/> 
<property name="mapperLocations" value="classpath:com/nyist/cn/Dao/Impl/UpfileDao.xml"/> 
</bean>

<!-- 配置mapper扫描器 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="sqlSessionFactory" ref="sqlSessionFactory"/>
<property name="basePackage" value="com.nyist.cn.Dao"/>
</bean>

</beans>


springmvc.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop" 
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans 
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd 
http://www.springframework.org/schema/mvc 
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd 
http://www.springframework.org/schema/context 
http://www.springframework.org/schema/context/spring-context-3.2.xsd 
http://www.springframework.org/schema/aop 
http://www.springframework.org/schema/aop/spring-aop-3.2.xsd 
http://www.springframework.org/schema/tx 
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd ">

<!-- 配置组件扫描 -->
<context:component-scan base-package="com.nyist.cn"></context:component-scan>

<!-- 配置mvc注解驱动 -->
<mvc:annotation-driven></mvc:annotation-driven>

<!-- 配置视图解析器 -->
<!-- 配置sprigmvc视图解析器:解析逻辑试图,前缀+逻辑试图+后缀====/WEB-INF/jsps/xxx.jsp -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/pages/"/>
<property name="suffix" value=".jsp"/>
</bean>

</beans>


(4)修改web.xml,配置控制器,加载以上两个配置文件,web.xml代码如下:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" 
xmlns="http://java.sun.com/xml/ns/javaee" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">

<!-- 配置字符编码过滤器 -->
<filter>
<filter-name>CharacterEncoding</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CharacterEncoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>


<!-- 配置自动装载配置文件的监听器ContenLoaderListener,自动装载配置文件 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<!-- 加载spring配置文件,当spring的配置文件在classpath下时,需要配置以下内容以供web容器进行加载 -->
 <!-- 如果不配置的时候,默认的路径是/WEB-INF/applicationContext.xml -->
 <context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>classpath:application.xml</param-value>
 </context-param>
 
 <!-- 配置控制器 -->
 <servlet>
  <servlet-name>UploadAndDownload</servlet-name>
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  <init-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>classpath:springmvc.xml</param-value>
  </init-param>
 </servlet>
 <servlet-mapping>
  <servlet-name>UploadAndDownload</servlet-name>
  <url-pattern>*.apex</url-pattern>
 </servlet-mapping>

</web-app>


(5)测试数据源能否获得

package com.nyist.cn.Test;


import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;


public class TestDataSource {

@Test
public void test1(){
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("application.xml");
Object obj = context.getBean("sqlSessionFactory");
System.out.println("Connection:"+obj);
}

}


运行结果:Connection:org.apache.ibatis.session.defaults.DefaultSqlSessionFactory@3349e9bb


二、ORM映射

(1)第一步Object,建实体Upfile.java,代码如下:

package com.nyist.cn.model;

//实体
public class Upfile {
private String id; //文件ID
private String uuidname; //uuid文件名称
private String filename; //文件的真实名称
private String savepath; //文件的保存路径
private String uptime; //文件上传时间
private String description; //文件的描述
private String username; //上传的用户

public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUuidname() {
return uuidname;
}
public void setUuidname(String uuidname) {
this.uuidname = uuidname;
}
public String getFilename() {
return filename;
}
public void setFilename(String filename) {
this.filename = filename;
}
public String getSavepath() {
return savepath;
}
public void setSavepath(String savepath) {
this.savepath = savepath;
}
public String getUptime() {
return uptime;
}
public void setUptime(String uptime) {
this.uptime = uptime;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public Upfile() {
super();
}
public Upfile(String id, String uuidname, String filename, String savepath, String uptime,String description, String username) {
super();
this.id = id;
this.uuidname = uuidname;
this.filename = filename;
this.savepath = savepath;
this.uptime = uptime;
this.description = description;
this.username = username;
}
@Override
public String toString() {
return "upfile [id=" + id + ", uuidname=" + uuidname + ", filename=" + filename + ", savepath=" + savepath
+ ", uptime=" + uptime + ",description="+description+", username=" + username + "]";
}
}

(2)第二部R,Relational,即数据库的关系表

①创建数据库

    //创建一个字符编码为UTF-8并且带有校对规则的数据库

    create database webUploadAndDownload character set utf8 collate utf8_general_ci;

②创建数据表

    create table upfile(

        id varhcar(40) primary key,

        uuidname varchar(100) not null,

        filename varchar(100) not null,

        savepath varchar(255) not null,

        uptime datetime not null,

       description varchar(255),

       username varchar(40) not null

    );


(3)第三步M,Mapping映射,使用Mybatis 的配置文件将Java对象映射到数据库表中

示例:

<insert id="addfile"  parameterType="com.nyist.cn.model.Upfile">
insert into upfile(id,uuidname,filename,savepath,uptime,description,username) values(#{id},#{uuidname},#{filename},#{savepath},#{uptime},#{description},#{username})

</insert>


(4)编写Dao层,为了是数据库和程序持久化,我们在配置文件中创建了Bean工厂,在实现Dao接口时,我采用配置配置文件来实现Dao中的方法

UpfileDao.java 如下:

package com.nyist.cn.Dao;


import java.util.List;


import com.nyist.cn.model.Upfile;


public interface UpfileDao {

//添加文件
public void addfile(Upfile upfile);

}


UpfileDaoImpl.xml如下:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper    
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"    
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">


<mapper namespace="com.nyist.cn.Dao.UpfileDao">
<insert id="addfile"  parameterType="com.nyist.cn.model.Upfile">
insert into upfile(id,uuidname,filename,savepath,uptime,description,username) values(#{id},#{uuidname},#{filename},#{savepath},#{uptime},#{description},#{username})
</insert>

<select id="getAllFile" resultType="com.nyist.cn.model.Upfile">
select * from upfile order by uptime desc
</select>

<select id="findUpfile" parameterType="java.lang.String" resultType="com.nyist.cn.model.Upfile">
select * from upfile where id = #{id}
</select>

<delete id="deleteupfile" parameterType="java.lang.String">
delete from upfile where id = #{id}
</delete>

</mapper>

(5)编写UpfileService接口和UpfileServiceImpl.java

UpfileService 接口如下:

package com.nyist.cn.Service;


import java.util.List;


import com.nyist.cn.model.Upfile;


public interface UpfileService {
//添加文件
public void addfile(Upfile upfile);

}

UpfileServiceImpl.java如下:

package com.nyist.cn.Service.Impl;


import java.util.List;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import com.nyist.cn.Dao.UpfileDao;
import com.nyist.cn.Service.UpfileService;
import com.nyist.cn.model.Upfile;


@Service
public class UpfileServiceImpl implements UpfileService{


@Autowired
private UpfileDao upfileDao ;

@Override
public void addfile(Upfile upfile) {
upfileDao.addfile(upfile);

}

}

(6)编写Controller

代码如下:

package com.nyist.cn.Controller;


import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.net.URLEncoder;
import java.util.List;


import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;


import com.nyist.cn.Service.UpfileService;
import com.nyist.cn.Utils.WebUtils;
import com.nyist.cn.model.Upfile;
@Controller
public class UpfileController {

@Autowired
private UpfileService upfileService ;
/**
*  后台 jsp 页面访问
* @return
*/
@RequestMapping("index")
public String index(){
return "index";
}

@RequestMapping("message")
public String message(){
return "message";
}

@RequestMapping("head")
public String head(){
return "head";
}

@RequestMapping("upload")
public String upload(){
return "upload";
}

@RequestMapping("showdownload")
public String showdownload(){
return "showdownload";
}


@RequestMapping("UploadAction")
public void Upload(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException, IllegalAccessException, InvocationTargetException{
//拿到前台传进来的数据   首先判断是否为mutipart/form-data提交方式
if(!ServletFileUpload.isMultipartContent(request)){
request.setAttribute("message","上传的不是为有效的数据类型");
request.getRequestDispatcher("/message.apex").forward(request, response);
return ;
}
//得到保存文件 的目录
String path = request.getSession().getServletContext().getRealPath("/WEB-INF/upload");
//制作WebUtils 工具类  封装request 和  savepath
Upfile upfile = WebUtils.doUpload(request,path);
upfileService.addfile(upfile);
System.out.println("Upfile:"+upfile);
request.setAttribute("message","上传成功!");
request.getRequestDispatcher("/message.apex").forward(request, response);
}

@RequestMapping("listfileAction")
public void listfile(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException{
String method = request.getMethod();
if("GET".equals(method)){
List<Upfile> list = upfileService.getAllFile();
request.setAttribute("list",list);
request.getRequestDispatcher("/showdownload.apex").forward(request, response);
return ;
}


@RequestMapping("DownLoadAction")
public void DownLoad(HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException{
//拿到前台数据
String id = request.getParameter("id");
Upfile upfile = upfileService.findUpfile(id);
System.out.println("Upfile:"+upfile);
File file = new File(upfile.getSavepath()+File.separator+upfile.getUuidname());
System.out.println("File:"+file);
if(!file.exists()){
request.setAttribute("message","下载资源已被删除");
request.getRequestDispatcher("/message.apex").forward(request, response);
return ;
}
response.setHeader("content-disposition","attachment;filename="+URLEncoder.encode(upfile.getFilename(),"UTF-8"));
try {
FileInputStream in = new FileInputStream(file);
OutputStream out = response.getOutputStream();
int len =0;
byte buffer[] = new byte[1024];
while((len = in.read(buffer))>0){
out.write(buffer, 0, len);
}
in.close();
} catch(FileNotFoundException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}

}


(7)测试运行结果如下


猜你喜欢

转载自blog.csdn.net/lvhaoguang0/article/details/81045322