spring boot上传 下载图片。
https://blog.csdn.net/a625013/article/details/52414470
build.gradle
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath('org.springframework.boot:spring-boot-gradle-plugin:1.5.9.RELEASE')
}
}
group "com.li"
version "1.0-SNAPSHOT"
apply plugin: "java" //java 插件
apply plugin: "org.springframework.boot" //spring boot 插件
apply plugin: "io.spring.dependency-management"
apply plugin: "application" //应用
//mainClassName = "Main.Application"
sourceCompatibility = 1.8
repositories {
mavenCentral()
}
dependencies {
compile("org.springframework.boot:spring-boot-starter-web",
"org.springframework.boot:spring-boot-starter-activemq",
"org.springframework.boot:spring-boot-starter-test",
"org.springframework.boot:spring-boot-starter-cache",
"org.springframework.boot:spring-boot-devtools")
runtime ("org.apache.tomcat.embed:tomcat-embed-jasper")
testCompile group: 'junit', name: 'junit', version: '4.12'
}
1:spring boot提供了读取服务器路径之外图片,文件的方法。
1.1 :上传方法
//上传的方法
@RequestMapping(method = RequestMethod.POST, value = "/upload")
public String handleFileUpload(@RequestParam("file") MultipartFile file,
RedirectAttributes redirectAttributes, HttpServletRequest request) {
// System.out.println(request.getParameter("member"));
if (!file.isEmpty()) { try {
Files.copy(file.getInputStream(), Paths.get(ROOT, file.getOriginalFilename()));
redirectAttributes.addFlashAttribute("message",
"You successfully uploaded " + file.getOriginalFilename() + "!");
} catch (IOException|RuntimeException e) {
redirectAttributes.addFlashAttribute("message", "Failued to upload " + file.getOriginalFilename() + " => " + e.getMessage());
}
} else {
redirectAttributes.addFlashAttribute("message", "Failed to upload " + file.getOriginalFilename() + " because it was empty");
} return "redirect:/";
}
1.2:

package com.li.controller; import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo;
import static org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn; import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ResourceLoader;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.UUID;
import java.util.stream.Collectors; @Controller
public class FileUploadController { // private static final Logger log = LoggerFactory.getLogger(FileUploadController.class); public static final String ROOT = "d://upload-dir"; private final ResourceLoader resourceLoader; @Autowired
public FileUploadController(ResourceLoader resourceLoader) {
this.resourceLoader = resourceLoader;
} @RequestMapping(method = RequestMethod.GET, value = "/")
public String provideUploadInfo(Model model) throws IOException { model.addAttribute("files", Files.walk(Paths.get(ROOT))
.filter(path -> !path.equals(Paths.get(ROOT)))
.map(path -> Paths.get(ROOT).relativize(path))
.map(path -> linkTo(methodOn(FileUploadController.class).getFile(path.toString())).withRel(path.toString()))
.collect(Collectors.toList())); return "uploadForm";
} //显示图片的方法关键 匹配路径像 localhost:8080/b7c76eb3-5a67-4d41-ae5c-1642af3f8746.png
@RequestMapping(method = RequestMethod.GET, value = "/{filename:.+}")
@ResponseBody
public ResponseEntity<?> getFile(@PathVariable String filename) { try {
return ResponseEntity.ok(resourceLoader.getResource("file:" + Paths.get(ROOT, filename).toString()));
} catch (Exception e) {
return ResponseEntity.notFound().build();
}
} //上传的方法
@RequestMapping(method = RequestMethod.POST, value = "/upload")
public String handleFileUpload(@RequestParam("file") MultipartFile file,
RedirectAttributes redirectAttributes, HttpServletRequest request) {
// System.out.println(request.getParameter("member"));
if (!file.isEmpty()) { try {
Files.copy(file.getInputStream(), Paths.get(ROOT, file.getOriginalFilename()));
redirectAttributes.addFlashAttribute("message",
"You successfully uploaded " + file.getOriginalFilename() + "!");
} catch (IOException|RuntimeException e) {
redirectAttributes.addFlashAttribute("message", "Failued to upload " + file.getOriginalFilename() + " => " + e.getMessage());
}
} else {
redirectAttributes.addFlashAttribute("message", "Failed to upload " + file.getOriginalFilename() + " because it was empty");
} return "redirect:/";
} // @RequestMapping("/save")
// public String save(@RequestParam(value = "file") MultipartFile file, userInfo uf, RedirectAttributes attributes, HttpServletRequest request) {
// if (uf != null) {
// if (!file.isEmpty()) {
// String fileName = UUID.randomUUID().toString().replaceAll("-", "") + file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
// String filePath ="/Users/thomas-wu/upload/" + fileName;
// System.out.println(filePath);
// try {
// file.transferTo(new File(filePath));
// } catch (IOException e) {
// e.printStackTrace();
// }
// uf.setHead_href("getimgs?address="+filePath);
// }
//
// }
// String result = userService.saveUser(uf);
// JSONObject jb = JSONObject.fromObject(result);
// if (jb.getInt("status") == 1 && "信息保存成功".equals(jb.getString("msg"))) {
// attributes.addFlashAttribute("error", "信息保存成功");
// return "redirect:/user";
// }
// attributes.addFlashAttribute("error", "信息保存失败");
// return "redirect:/edit";
// } @RequestMapping("/getimgs")
public void getimg(String address, HttpServletRequest request, HttpServletResponse response) throws IOException{
try {
FileInputStream hFile=new FileInputStream(address);
int i=hFile.available();
byte data[]=new byte[i];
hFile.read(data);
hFile.close();
response.setContentType("image/*");
OutputStream toClient=response.getOutputStream();
toClient.write(data);
toClient.close();
}catch (IOException e){
PrintWriter toClient=response.getWriter();
response.setContentType("text/html;charset=gb2312");
toClient.write("无法打开图片");
toClient.close();
} } }
spring boot上传 下载图片。的更多相关文章
- springboot(十七):使用Spring Boot上传文件
上传文件是互联网中常常应用的场景之一,最典型的情况就是上传头像等,今天就带着带着大家做一个Spring Boot上传文件的小案例. 1.pom包配置 我们使用Spring Boot最新版本1.5.9. ...
- (转)Spring Boot(十七):使用 Spring Boot 上传文件
http://www.ityouknow.com/springboot/2018/01/12/spring-boot-upload-file.html 上传文件是互联网中常常应用的场景之一,最典型的情 ...
- 使用Spring Boot上传文件
原文:http://www.cnblogs.com/ityouknow/p/8298344.html 上传文件是互联网中常常应用的场景之一,最典型的情况就是上传头像等,今天就带着带着大家做一个Spri ...
- Spring Boot(十七):使用 Spring Boot 上传文件
上传文件是互联网中常常应用的场景之一,最典型的情况就是上传头像等,今天就带着带着大家做一个 Spring Boot 上传文件的小案例. 1.pom 包配置 我们使用 Spring Boot 版本 ...
- Spring Boot(十七):使用Spring Boot上传文件
Spring Boot(十七):使用Spring Boot上传文件 环境:Spring Boot最新版本1.5.9.jdk使用1.8.tomcat8.0 一.pom包配置 <parent> ...
- Spring框架学习(8)spring mvc上传下载
内容源自:spring mvc上传下载 如下示例: 页面: web.xml: <?xml version="1.0" encoding="UTF-8"?& ...
- Spring Boot上传文件(带进度条)
Spring Boot 上传文件(带进度条)# 配置文件 spring: freemarker: template-loader-path: classpath:/static/ ##Spring B ...
- 高可用的Spring FTP上传下载工具类(已解决上传过程常见问题)
前言 最近在项目中需要和ftp服务器进行交互,在网上找了一下关于ftp上传下载的工具类,大致有两种. 第一种是单例模式的类. 第二种是另外定义一个Service,直接通过Service来实现ftp的上 ...
- WebService上传下载图片
WebService服务端 接受要上传的图片 public string UploadImg(byte[] fileBytes, int id) { try { string filePath = M ...
随机推荐
- 【Spring源码深度解析学习系列】Bean的加载(六)
Bean的加载所涉及到的大致步骤: 1)转换对应beanName 为什么需要转换beanName呢?因为传入的参数可能是别名,也可能是FactoryBean,所以需要一系列的解析,这些解析内容包括如下 ...
- 【大数据系列】在hadoop2.8.0下配置SecondaryNameNode
修改namenode上的hdfs-site.xml configuration> <property> <name>dfs.replication</name> ...
- C++ #include—尖括号和双引号的区别
如果你还看一些别的C++教程,那么你可能很早就发现了,有些书上的#include命令写作#include <文件名>,但有时候又会出现#include "文件名".你会 ...
- Android studio快捷键设置
Android Studio格式化代码设置和代码风格设置.代码提示键 http://blog.csdn.net/u010156024/article/details/48207145 Android ...
- win10 与linux mint双系统 只能进入mint而无法进入windows的解决方案
新购买了一块ssd,和以前的hdd硬盘一起装双系统:win10和mint ssd:win10 sdb1 sdb2 sdb3 sda2 hdd: mint sda1 ...
- Gnome排序
Gnome排序(地精排序),起初由Hamid Sarbazi-Azad 于2000年提出,并被称为stupid排序,后来被Dick Grune描述并命名为“地精排序”,作为一个排序算法,和插入排序类似 ...
- linux shell脚本中 mode=${1:-sart} filename=${fileuser:-"filename"}
$1代表第二个参数m=${1:-start}表示如果$1存在且不为空,m就是$1如果$1不存在或为空,那么m就是start filename=${fileuser:-"filename&qu ...
- jQuery的ajax跨域 Jsonp原理
1.Jsonp Jsonp(json with padding)是JSON的一种“使用模式”,可用于解决主流浏览器的跨域数据访问的问题. Jsonp是为了解决ajax跨域发送http请求出现的,利用S ...
- PHPStorm 注册码&主题皮肤
JetBrains PhpStorm 注册方法: 用浏览器打开 http://idea.lanyus.com/ 点击页面中的“获得注册码” 然后打开PhpStorm,在注册时切换至Activation ...
- Git - Pull Request工作流
Pull Requests是Bitbucket上方便开发者之间协作的功能.提供了一个用户友好的Web界面,在集成提交的变更到正式项目前可以对变更进行讨论. 开发者向团队成员通知功能开发已经完成,Pul ...