springmvc和servlet在上传和下载文件(保持文件夹和存储数据库Blob两种方式)
参与该项目的文件上传和下载。一旦struts2下完成,今天springmvc再来一遍。发现springmvc特别好包,基本上不具备的几行代码即可完成,下面的代码贴:
FileUpAndDown.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<html>
<head>
<title>using commons Upload to upload file</title>
</head>
<script type="text/javascript">
function downFile(){
var fileId = document.getElementById("fileId").value;
location.href="fileDownload?fileId=" + fileId;
}
</script>
<style>
* {
font-family: "宋体";
font-size: 14px
}
</style>
<body>
<p align="center">文件上传下载</p>
<form id="form1" name="form1" method="post" action="fileUpload" enctype="multipart/form-data">
<table border="0" align="center">
<tr>
<td>上传文件:</td>
<td><input name="file" type="file" size="20"></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="提交"> <input type="reset" name="reset" value="重置"></td>
</tr>
</table>
</form>
<div align="center">
<input type="text" id="fileId"><input type="button" value="依据Id下载文件" onclick="javascript:downFile()">
</div>
</body>
</html>
FileUpAndDownController.java
@RequestMapping(value = "/fileUpload")
public String upload(
@RequestParam(value = "file", required = false) MultipartFile file,
HttpServletRequest request, ModelMap model) throws IOException { /*
// 方式一:保存文件文件夹
try {
String path = request.getSession().getServletContext().getRealPath("/");// 文件保存文件夹,也可自定为绝对路径
String fileName = file.getOriginalFilename();// getOriginalFilename和getName是不一样的哦
System.out.println(path);
File targetFile = new File(path, fileName);
if (!targetFile.exists()) {
targetFile.mkdirs();
}
file.transferTo(targetFile);
model.addAttribute("upload.message", request.getContextPath() + "/upload/" + fileName);
} catch (Exception e) {
e.printStackTrace();
}
*/
// 方式二:保存入库
Map<String, Object> insertMap = new HashMap<String, Object>();
insertMap.put("byt", file.getBytes());
insertMap.put("fileName", file.getOriginalFilename()); int flag = fileUpAndDownMapper.saveFileInfo(insertMap);
if(flag > 0)
model.addAttribute("upload.message", "success");
else
model.addAttribute("upload.message", "failure");
return "/core/param/businessparam/uploadResult";
}
FileUpAndDownMapper.xml(相应的数据库为db2,保存blob类型)
<?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.xx.persistence.FileUpAndDownMapper"> <resultMap id="fileBean" type="com.xx.web.FileUpAndDown">
<id column="ID" property="id" jdbcType="INTEGER" />
<result column="FILENAME" property="fileName" jdbcType="VARCHAR" />
<result column="TESTA" property="testa" javaType="byte[]" jdbcType="BLOB" typeHandler="org.apache.ibatis.type.BlobTypeHandler" />
<result column="FILESTREAM" property="fileStream" javaType="byte[]" jdbcType="BLOB" typeHandler="org.apache.ibatis.type.BlobTypeHandler" />
</resultMap> <insert id="saveFileInfo" parameterType="java.util.HashMap">
INSERT INTO BLOBTEST(FILENAME, FILESTREAM)
VALUES(#{fileName}, #{byt, javaType=byte[], jdbcType=BLOB, typeHandler=org.apache.ibatis.type.BlobTypeHandler})
</insert> <select id="getFileByPk" resultMap="fileBean" parameterType="int">
SELECT * FROM BLOBTEST WHERE ID=${value}
</select>
</mapper>
uploadResult.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head> <title>uploadResult</title> <meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
</head>
<body>
<a href="fileManagePage">上传文件</a> ${requestScope['upload.message'] }
</body>
</html>
以上为springmvc下上传文件的Demo,当中非常关键的一步是。spring的配置文件里要增加文件上传的支持:
<!-- 支持上传文件 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/>
文件的保存做了两种方式,一种是直接存server的文件文件夹;还有一种是把文件流存入数据库blob字段内(项目的特须要求)
以下是文件下载的代码:
@ResponseBody
@RequestMapping(value = "/fileDownload")
public void fileDownload(HttpServletRequest request,
HttpServletResponse response) throws IOException {
String fileId = request.getParameter("fileId");
FileUpAndDown file = fileUpAndDownMapper.getFileByPk(Integer.parseInt(fileId));
byte[] fileStream = file.getFileStream();
String fileName = file.getFileName(); // 以流的形式下载文件
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment; filename=\"" + new String(fileName.getBytes("gb2312"), "ISO8859-1" ) + "\"");
OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
toClient.write(fileStream);
toClient.flush();
toClient.close();
}
springmvc下文件上传下载非常easy明对?不喜欢servlet在这么多的代码。
springmvc和servlet在上传和下载文件(保持文件夹和存储数据库Blob两种方式)的更多相关文章
- 微信小程序云开发-云存储-上传、下载、打开文件文件(word/excel/ppt/pdf)一步到位
一.wxml文件 <!-- 上传.下载.打开文件一步执行 --> <view class="handle"> <button bindtap=&quo ...
- springmvc模式下的上传和下载
接触了springmvc模式后,对上一次的上传与下载进行优化, 上次请看这里. 此处上传的功能依旧是采用表格上传.文件格式依旧是 <form action="${pageContext ...
- PHP实现文件上传和下载(单文件上传、多文件上传、多个单文件上传)(面向对象、面向过程)
今天我们来学习用PHP进行文件的上传和下载,并且用面向过程和面向对象的方式对文件上传进行一个限制 一.简单的上传测试 1.客户端:upload.php 2.后端:doAction.php 结果: 二. ...
- WCF上传、下载、删除文件
关键代码: --上传的stream处理,转为bytep[] private void Parse(Stream stream, Encoding encoding) { this.Success = ...
- mvc上传,下载,浏览文件功能(用uploadify插件)
类 public class UpLoadFileController : Controller { // // GET: /UpLoadFile/ public ActionResult Index ...
- aspx 文件上传和下载,多文件上传
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="MultiFileUpload. ...
- Struts2实现文件上传和下载,多文件上传,限制文件大小,限制文件类型
文件上传使用的包:commons-upload-xx.jar commons-io-xx.jar 一.实现文件上传: 1.在表单空间中添 ...
- php实现文件上传,下载的常见文件配置
配置文件,php.ini uploadfile post_max_size 规定表单上传的最大文件:
- Open XML的上传、下载 、删除 ......文件路径
/// <summary> /// Get download site, if download tempfolder not existed, create it first /// & ...
随机推荐
- 辛星整理3linux笔记,免费下载点,我希望对你有所帮助
忙乱,这是我第一次看李指出老师的视频时,,这本书是关于116页面,在csdn下载对:点我下载 ,假设左边的地址崩溃了,也能够在浏览器中输入例如以下地址然后下载:http://download.csdn ...
- 新秀学习SSH(十四)——Spring集装箱AOP其原理——动态代理
之前写了一篇文章IOC该博客--<Spring容器IOC解析及简单实现>,今天再来聊聊AOP.大家都知道Spring的两大特性是IOC和AOP. IOC负责将对象动态的注入到容器,从而达到 ...
- CentOS7 安装zookeeper
本章介绍CentOS的初始配置与zookeeper的安装. www.apache.org/dist/上可以下载Hadoop整个生态环境的组件,我下的Zookeeper3.4.6版本 我一般都是在一个虚 ...
- 使 IIS 6.0 可以在 64 位 Windows 上运行 32 位应用程序 试图加载格式不正确的程序。
原文 使 IIS 6.0 可以在 64 位 Windows 上运行 32 位应用程序 试图加载格式不正确的程序. win7 64位操作系统上边运行IIS网站应用的时候,提示错误"试图加载格式 ...
- Oracle 数据导出到PowerDesigner
原文:Oracle 数据导出到PowerDesigner [一]配置ODBC win7 :控制面板(查看方式:小图标)→管理工具→数据源(ODBC) 在[ODBC数据源管理器]面板下,在默认[用户DN ...
- JavaScript中null和undefined的总结
先说null,它表示一个特殊值,常用来描述“空值”.对null执行typeof运算,结果返回字符串“object”,也就是说,可以将null认为是一个特殊的对象值,含义是“非对象”(感觉怪怪的).实际 ...
- Matlab.NET混合编程技巧之——直接调用Matlab内置函数(附源码)
原文:[原创]Matlab.NET混合编程技巧之--直接调用Matlab内置函数(附源码) 在我的上一篇文章[原创]Matlab.NET混编技巧之——找出Matlab内置函数中,已经大概的介绍了mat ...
- Sicily 1299 Academy Awards (map + vector)集装箱
链接:http://soj.me/show_problem.php?pid=1299&cid= Description Selected from 3,850 teams from 1,329 ...
- Android JNI环境要SQLite加密模块简介
免费的SQLite开源源代码仅仅给提供了两个函数,仅仅有实现这两个函数才干实现数据库总体加密. 然后废了点劲从网上找了一个已经实现好的开源库http://sourceforge.net/project ...
- bigdata_hiveserver2报错_thrift
问题一: php客户端,链接hiveserver2 ,报错 如下 1: server.TThreadPoolServer (TThreadPoolServer.java:run(215)) - Err ...