单文件上传

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. hbase使用MapReduce操作4(实现将 HDFS 中的数据写入到 HBase 表中)

    实现将 HDFS 中的数据写入到 HBase 表中 Runner类 package com.yjsj.hbase_mr2; import com.yjsj.hbase_mr2.ReadFruitFro ...

  2. [IOS] 详解图片局部拉伸 + 实现图片局部收缩

    (图为微信首页右上角『+』效果) 当初还在开发WP7的时候,从IOS同事那边了解到类似微信以上功能的实现. Item条数不同,总高度也不同,这就需要将背景图片进行局部拉伸到响应的高度,并且保持上方的三 ...

  3. PHP Functions - arsort()

    <?php $characters = array('a','b','c','d','e','f'); arsort($characters); print_r($characters); /* ...

  4. delphi 手机振动 IOS Android

    delphi 手机振动 IOS Android delphi  手机振动 IOS Android 振动 https://community.embarcadero.com/blogs/entry/ho ...

  5. Spark Structured Stream 2

    ❤Limitations of DStream API Batch Time Constraint application级别的设置. 不支持EventTime event time 比process ...

  6. Asp.Net从相对路径获取绝对路径的方法(不需要httpcontext上下文也可)

    //如果拿不到当前HttpContext上下文的话可以用该方法取得绝对路径 var filePath = HostingEnvironment.MapPath("需要获取绝对路径 的 相对路 ...

  7. 知识记录:ASP.NET 应用程序生命周期概述及Global.asax文件中的事件

    IIS7 ASP.NET 应用程序生命周期概述 https://msdn.microsoft.com/zh-cn/library/bb470252(v=vs.100).aspx HttpApplica ...

  8. day 94 RestFramework序列化组件与视图view

    一 .复习 1. CBV流程 class BookView(View): def get(): pass def post(): pass #url(r'^books/', views.BookVie ...

  9. 程序媛计划——mysql连接表

    #inner join等值连接/内连接 mysql> select * from info; +------+-------------+----------+ | name | phone | ...

  10. 程序媛计划——mysql基本操作

    本文适用于mac 在官网上下载community 版mysql,选择dmy这种.在终端中安装好mysql. #进入mysql /usr/local/mysql/bin/mysql -uroot -p ...