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 ...
随机推荐
- ajax二级联动代码实例
//二级联动 $(function () { var _in_progress = false; function check_in_progress() { if (_in_progress == ...
- Money型字段小数点后保留两位小数
asp.net直接显示Money型字段小数点后面将保留四位小数,而我们常见的格价显示一般是小数点后两位,如何实现这种效果呢,有如下几种方法: 1.直接型,通过ToString()函数直接格式话 例如把 ...
- storm事务
1. storm 事务 对于容错机制,Storm通过一个系统级别的组件acker,结合xor校验机制判断一个msg是否发送成功,进而spout可以重发该msg,保证一个msg在出错的情况下至少被重发一 ...
- 【CF888E】Maximum Subsequence 折半搜索
[CF888E]Maximum Subsequence 题意:给你一个序列{ai},让你从中选出一个子序列,使得序列和%m最大. n<=35,m<=10^9 题解:不小心瞟了一眼tag就一 ...
- intellij idea如何快速格式化代码
选中代码,一键格式化代碼: Ctrl+Alt+L
- [转][darkbaby]任天堂传——失落的泰坦王朝(中)
TV游戏产业历史上曾有过太多表里不一的外交辞令,然而当年SQUARE和任天堂分道扬镳的真正原因确实如坂口博信在1996年2月29日的PS版 <FFVII>发表会上宣称的那样:“虽然之前有过 ...
- 3种方法教你PS快速去掉水印
方法一:使用选框工具 勾选水印部分: 按住Shift+f5选择内容识别: 然后 ctrl+d 取消选择,水印就去掉了 PS:其实这个方法有个快捷办法,直接使用选框工具选中之后,按Delete就可以弹出 ...
- Hive desc
Describe Database hive> DESCRIBE DATABASE test; test ??? hdfs://ns1/user/hive/warehouse/test.db w ...
- 爬虫之requests详解
requests Python标准库中提供了:urllib.urllib2.httplib等模块以供Http请求,但是,它的 API 太渣了.它是为另一个时代.另一个互联网所创建的.它需要巨量的工作, ...
- 9.8Django
2018-9-8 14:34:38