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 ...
随机推荐
- PHP curl登录 跳过验证码
<?php switch($_GET['do']){ case 'vc': $cookieFile = "./test.tmp"; $url = 'http://localh ...
- 虚拟机可以ping同宿主机,宿主机ping不通虚拟机
虚拟机里能ping同本机,而本机却ping不通虚拟机,或者虚拟机不能ping通本机,可能有如下原因: 如果是桥接模式,那么可能性1:虚拟机防火墙禁ping,请关闭虚拟机防火墙重试:root 状态下se ...
- Excel中countif函数的使用方法
1.countif函数的含义 在指定区域中按指定条件对单元格进行计数(单条件计数) 建议和countifs函数结合起来学习,可以观看小编的经验Excel中countifs函数的使用方法. END 2. ...
- LeetCode 23 Merge k Sorted Lists(合并k个有序链表)
题目链接: https://leetcode.com/problems/merge-k-sorted-lists/?tab=Description Problem: 给出k个有序的list, 将其进行 ...
- JavaScript 异步进化史
前言 JS 中最基础的异步调用方式是 callback,它将回调函数 callback 传给异步 API,由浏览器或 Node 在异步完成后,通知 JS 引擎调用 callback.对于简单的异步操作 ...
- linux route命令详解
考试题一:linux下如何添加路由(百度面试题) 以上是原题,老男孩老师翻译成如下3道题. a.如何用命令行方式给linux机器添加一个默认网关,假设网关地址为10.0.0.254? b. 192.1 ...
- MySQL优化之SQL耗时瓶颈 SHOW profiles
1.首先查看是否开启profiling功能 SHOW VARIABLES LIKE '%pro%'; 或者 SELECT @@profiling; 2.开启profiling SET profilin ...
- [工具] f.lux – 随时间改变屏幕色温护眼
f.lux 是一款根据时间变化来改变屏幕色温的软件.让你在深夜也能感受到太阳的温暖,顺便还有助于睡眠. 在 f.lux 里,首先设置一个适合你的变化色温范围,白天的色温控制在 6500K 以下,晚上的 ...
- 8.11 数据库ORM(5)
2018-8-11 20:43:52 昨天从俺弟家回来了. 和俺弟聊天发现,他一直停留在自己目前的圈子,自己觉得很牛逼,比别人高人一等,, 读书无用论,,可以用 幸存者偏激理论 大概就是这个 可以否决 ...
- 洛谷P2178 品酒大会【后缀数组】【单调栈】
题目描述 一年一度的“幻影阁夏日品酒大会”隆重开幕了.大会包含品尝和趣味挑战 两个环节,分别向优胜者颁发“首席品酒家”和“首席猎手”两个奖项,吸引了众多品酒师参加. 在大会的晚餐上,调酒师 Rainb ...