单文件上传

1, 需要使用thymeleaf模板:  http://www.cnblogs.com/wenbronk/p/6565834.html

src/main/resource/template/file.html

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
<title>Hello World!</title>
</head>
<body>
<form method="POST" enctype="multipart/form-data" action="/upload">
<p>文件:<input type="file" name="file" /></p>
<p><input type="submit" value="上传" /></p>
</form>
</body>
</html>

文件上传方法

package com.iwhere.main.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;
import java.util.UUID; import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest; /**
* 文件上传controller
*
* @RestController 相当于同时 @Controller和@ResponseBody两个注解
*
* @author wenbronk
* @time 2017年4月6日 下午2:43:03 2017
*/
@RestController
public class FileUploadController { /**
* 文件上传
*
* @return
*/
@RequestMapping(value = "/upload", method = RequestMethod.POST)
public String handlFileUpload(@RequestParam("file") MultipartFile file) { if (file.isEmpty()) {
return "文件是空的";
} // 读取文件内容并写入 指定目录中
String fileName = file.getOriginalFilename();
// String suffixName = fileName.substring(fileName.lastIndexOf("."));
fileName = UUID.randomUUID() + "|+=|-|" + fileName; File dest = new File("E:/test/" + fileName);
// 判断目录是否存在
if (!dest.getParentFile().exists()) {
dest.getParentFile().mkdirs();
} try {
file.transferTo(dest);
} catch (IOException e) {
return "后台也不知道为什么, 反正就是上传失败了";
}
return "上传成功";
}
}

多文件上传:

1, thymeleaf

src/main/resource/template/multifile.html

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
<title>Hello World!</title>
</head>
<body>
<form method="POST" enctype="multipart/form-data" action="/batch/upload">
<p>文件1:<input type="file" name="file" /></p>
<p>文件2:<input type="file" name="file" /></p>
<p>文件3:<input type="file" name="file" /></p>
<p><input type="submit" value="上传" /></p>
</form>
</body>
</html>

2, 多文件上传方法

    /**
* 多文件上传
* 类似单文件上传, 遍历
* @return
*/
@RequestMapping(value = "multiUpload", method = RequestMethod.POST)
public String handleMultiFileupload(HttpServletRequest request) {
List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file"); for (MultipartFile multipartFile : files) {
if (multipartFile.isEmpty()) {
return "文件是空的";
} // 读取文件内容并写入 指定目录中
String fileName = multipartFile.getOriginalFilename();
// String suffixName =
// fileName.substring(fileName.lastIndexOf("."));
fileName = UUID.randomUUID() + "|+=|-|" + fileName; File dest = new File("E:/test/" + fileName);
// 判断目录是否存在
if (!dest.getParentFile().exists()) {
dest.getParentFile().mkdirs();
} try {
multipartFile.transferTo(dest);
} catch (IOException e) {
return "后台也不知道为什么, 反正就是上传失败了";
}
}
return "上传成功";
}

文件下载

/**
* 文件下载
*
* @return
*/
@RequestMapping("/download")
public String downLoadFile(HttpServletRequest request, HttpServletResponse response) {
// 文件名可以从request中获取, 这儿为方便, 写死了
String fileName = "rtsch_ex.json";
// String path = request.getServletContext().getRealPath("/");
String path = "E:/test";
File file = new File(path, fileName); if (file.exists()) {
// 设置强制下载打开
response.setContentType("application/force-download");
// 文件名乱码, 使用new String() 进行反编码
response.addHeader("Content-Disposition", "attachment;fileName=" + fileName); // 读取文件
BufferedInputStream bi = null;
try {
byte[] buffer = new byte[];
bi = new BufferedInputStream(new FileInputStream(new File("")));
ServletOutputStream outputStream = response.getOutputStream();
int i = -;
while (- != (i = bi.read(buffer))) {
outputStream.write(buffer, , i);
}
return "下载成功";
} catch (Exception e) {
return "程序猿真不知道为什么, 反正就是下载失败了";
} finally {
if (bi != null) {
try {
bi.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
return "文件不存在";
}

文件下载时, 最容易出现文件名乱码的问题, 这儿使用new String() 进行反编码,

String downname = new String(filename.getBytes("gbk"),"iso8859-1");

当然还有个不太稳的方法:

URLEncoder.encode(fileName, "UTF-8"));  

还有一种, 不太奏效

springboot-17-springboot的文件上传和下载的更多相关文章

  1. SpringBoot整合阿里云OSS文件上传、下载、查看、删除

    1. 开发前准备 1.1 前置知识 java基础以及SpringBoot简单基础知识即可. 1.2 环境参数 开发工具:IDEA 基础环境:Maven+JDK8 所用技术:SpringBoot.lom ...

  2. springboot+web文件上传和下载

    一.首先安装mysql数据库,开启web服务器. 二.pom.xml文件依赖包配置如下: <?xml version="1.0" encoding="UTF-8&q ...

  3. SpringBoot 文件上传、下载、设置大小

    本文使用SpringBoot的版本为2.0.3.RELEASE 1.上传单个文件 ①html对应的提交表单 <form action="uploadFile" method= ...

  4. SpringBoot下文件上传与下载的实现

    原文:http://blog.csdn.net/colton_null/article/details/76696674 SpringBoot后台如何实现文件上传下载? 最近做的一个项目涉及到文件上传 ...

  5. 七、springBoot 简单优雅是实现文件上传和下载

    前言 好久没有更新spring Boot 这个项目了.最近看了一下docker 的知识,后期打算将spring boot 和docker 结合起来.刚好最近有一个上传文件的工作呢,刚好就想起这个脚手架 ...

  6. springboot整合OSS实现文件上传

    OSS 阿里云对象存储服务(Object Storage Service,简称 OSS),是阿里云提供的海量.安全.低成本.高可靠的云存储服务.OSS可用于图片.音视频.日志等海量文件的存储.各种终端 ...

  7. 精讲响应式WebClient第4篇-文件上传与下载

    本文是精讲响应式WebClient第4篇,前篇的blog访问地址如下: 精讲响应式webclient第1篇-响应式非阻塞IO与基础用法 精讲响应式WebClient第2篇-GET请求阻塞与非阻塞调用方 ...

  8. 学习SpringMVC必知必会(7)~springmvc的数据校验、表单标签、文件上传和下载

    输入校验是 Web 开发任务之一,在 SpringMVC 中有两种方式可以实现,分别是使用 Spring 自带的验证 框架和使用 JSR 303 实现, 也称之为 spring-validator 和 ...

  9. java web学习总结(二十四) -------------------Servlet文件上传和下载的实现

    在Web应用系统开发中,文件上传和下载功能是非常常用的功能,今天来讲一下JavaWeb中的文件上传和下载功能的实现. 对于文件上传,浏览器在上传的过程中是将文件以流的形式提交到服务器端的,如果直接使用 ...

  10. (转载)JavaWeb学习总结(五十)——文件上传和下载

    源地址:http://www.cnblogs.com/xdp-gacl/p/4200090.html 在Web应用系统开发中,文件上传和下载功能是非常常用的功能,今天来讲一下JavaWeb中的文件上传 ...

随机推荐

  1. windows下C++实现遍历本地文件

    1.假设本地 d:/ 下存放着0.txt,1.txt两个文件 2.开发工具VS,开发语言C++,怎么遍历得到两个文件呢? 废话不多,具体代码请看下面: /** * 入参:文件存放文件夹路径,例如D:\ ...

  2. opencv学习_4(opencv基础数据结构 CvPoint & CvSize & CvRect & CvScalar & CvArr & CvMat)

    1:包含在cxcore/include/cxtypes.h头文件中. 2:CvPoint系列   -----(x,y) CvPoint:表示图像中的点 CvPoint2D32f:二维空间中的点 CvP ...

  3. Hibernate和spring中的session总结

    1.this.getSession() 是org.springframework.orm.hibernate3.support.HibernateDaoSupport 中的一个方法,它可以从当前事务或 ...

  4. svn服务器快速搭建及简单配置

    http://www.360doc.com/content/11/0711/19/5131531_132950891.shtml 简介Svn已经不容质疑的成为了一款流行的代码控制工具,但是你是否还在为 ...

  5. Mongodb 与 SQL 语句对照表

    In addition to the charts that follow, you might want to consider the Frequently Asked Questions sec ...

  6. Linux - 修改文件编码

    enca -L zh_CN -x UTF- file

  7. 【 PLSQL Developer安装、tnsnames.ora配置 解答】

    使用plsql远程连接数据库需要安装plsql工具+ oracle的远程客户端 在不登录的状态打开plsql: 点击工具---首选项:指定oracle客户端的安装路径: C:\javaSoft\PLS ...

  8. leetcode 搜索插入位置

    给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引.如果目标值不存在于数组中,返回它将会被按顺序插入的位置. 你可以假设数组中无重复元素. 示例 1: 输入: [1,3,5,6], 5 输 ...

  9. PropertyPlaceHolderConfigurer中的location是不是用错了?

    本文由作者张远道授权网易云社区发布. spring中常用PropertyPlaceHolderConfigurer来读取properties配置文件的配置信息.常用的配置方式有两种,一种是使用loca ...

  10. python 使用 response.read() 接收 json 数据

    import json result = response.read() result.decode('utf-8') jsonData = json.loads(result)