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 ...
随机推荐
- Android学习之位图BitMap
BitMap代表一张位图,扩展名可以是.bmp或者.dib.位图是Windows标准格式图形文件,它将图像定义为由点(像素)组成,每个点可以由多种色彩表示,包括2.4.8.16.24和32位色彩.例如 ...
- Form表单验证神器: BootstrapValidator
前言:做Web开发的我们,表单验证是再常见不过的需求了.友好的错误提示能增加用户体验.博主搜索bootstrap表单验证,搜到的结果大部分都是文中的主题:bootstrapvalidator.今天就来 ...
- Esper学习之十一:EPL语法(七)
上一篇说到了EPL如何访问关系型数据库这种数据源,实际上别的数据源,比如:webservice.分布式缓存.非关系型数据库等等,Esper提供了统一的数据访问接口.然后今天会讲解如何创建另外一种事件类 ...
- 利用腾讯云COS云对象存储定时远程备份网站
版权声明:本文由张戈 原创文章,转载请注明出处: 文章原文链接:https://www.qcloud.com/community/article/942851001487125915 来源:腾云阁 h ...
- JavaScript 浮点数陷阱及解法
众所周知,JavaScript 浮点数运算时经常遇到会 0.000000001 和 0.999999999 这样奇怪的结果,如 0.1+0.2=0.30000000000000004.1-0.9=0. ...
- Android studio 插件安装
安装插件步骤 一 CodeGlance 最大的用途:可用于快速定位代码.显示在右侧 二 Android Studio Prettify 可以将代码中的字符串写在string.xml文件中 选中字符串鼠 ...
- Sencha Touch 扩展集合
https://market.sencha.com/extensions http://try.sencha.com/touch/2.1.0/ http://www.mitchellsimoens.c ...
- Linux下进程隐藏的方法及其对抗
零.背景 在应急响应中,经常碰到ps命令和top命令查不到恶意进程(异常进程)的情况,会对应急响应造成很大的影响.轻则浪费时间,重则排查不出问题,让黑客逍遥法外.所以这篇博客研究学习如何对抗linux ...
- Metaspolit使用简介
信息收集阶段 Whois信息收集 msf auxiliary > whois baidu.com 域名信息查询阶段 msf auxiliary > nslookup www.baidu.c ...
- 原生JS实现ajax 发送post请求
1. [代码]原生JS实现ajax 发送post请求 <script> var oStr = ''; var postData = {}; var oAjax = null; //post ...