spring boot实现图片上传和下载功能

这篇博客简单介绍下spring boot下图片上传和下载,已经遇到的问题。首先需要创建一个spring boot项目。

1、核心的controller代码

package com.qwrt.station.websocket.controller; 

import com.alibaba.fastjson.JSONObject;
import com.qwrt.station.common.util.JsonUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
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 javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*; 

/**
 * Created by jack on 2017/10/30.
 */
@RestController
@RequestMapping("v1/uploadDownload")
public class UploadDownloadController {
 private static final Logger logger = LoggerFactory.getLogger(UploadDownloadController.class);
 @Value("${uploadDir}")
 private String uploadDir; 

 @RequestMapping(value = "/uploadImage", method = RequestMethod.POST)
 public JSONObject uploadImage(@RequestParam(value = "file") MultipartFile file) throws RuntimeException {
 if (file.isEmpty()) {
  return JsonUtil.getFailJsonObject("文件不能为空");
 }
 // 获取文件名
 String fileName = file.getOriginalFilename();
 logger.info("上传的文件名为:" + fileName);
 // 获取文件的后缀名
 String suffixName = fileName.substring(fileName.lastIndexOf("."));
 logger.info("上传的后缀名为:" + suffixName);
 // 文件上传后的路径
 String filePath = uploadDir;
 // 解决中文问题,liunx下中文路径,图片显示问题
 // fileName = UUID.randomUUID() + suffixName;
 File dest = new File(filePath + fileName);
 // 检测是否存在目录
 if (!dest.getParentFile().exists()) {
  dest.getParentFile().mkdirs();
 }
 try {
  file.transferTo(dest);
  logger.info("上传成功后的文件路径未:" + filePath + fileName);
  return JsonUtil.getSuccessJsonObject(fileName);
 } catch (IllegalStateException e) {
  e.printStackTrace();
 } catch (IOException e) {
  e.printStackTrace();
 }
 return JsonUtil.getFailJsonObject("文件上传失败");
 } 

 //文件下载相关代码
 @RequestMapping(value = "/downloadImage",method = RequestMethod.GET)
 public String downloadImage(String imageName,HttpServletRequest request, HttpServletResponse response) {
 //String fileName = "123.JPG";
 logger.debug("the imageName is : "+imageName);
 String fileUrl = uploadDir+imageName;
 if (fileUrl != null) {
  //当前是从该工程的WEB-INF//File//下获取文件(该目录可以在下面一行代码配置)然后下载到C:\\users\\downloads即本机的默认下载的目录
  /* String realPath = request.getServletContext().getRealPath(
   "//WEB-INF//");*/
  /*File file = new File(realPath, fileName);*/
  File file = new File(fileUrl);
  if (file.exists()) {
  response.setContentType("application/force-download");// 设置强制下载不打开
  response.addHeader("Content-Disposition",
   "attachment;fileName=" + imageName);// 设置文件名
  byte[] buffer = new byte[1024];
  FileInputStream fis = null;
  BufferedInputStream bis = null;
  try {
   fis = new FileInputStream(file);
   bis = new BufferedInputStream(fis);
   OutputStream os = response.getOutputStream();
   int i = bis.read(buffer);
   while (i != -1) {
   os.write(buffer, 0, i);
   i = bis.read(buffer);
   }
   System.out.println("success");
  } catch (Exception e) {
   e.printStackTrace();
  } finally {
   if (bis != null) {
   try {
    bis.close();
   } catch (IOException e) {
    e.printStackTrace();
   }
   }
   if (fis != null) {
   try {
    fis.close();
   } catch (IOException e) {
    e.printStackTrace();
   }
   }
  }
  }
 }
 return null;
 } 

}

上面的代码有两个方法,上面的方法是图片上传的方法,下面的方法是图片下载的方法。下载图片需要传入图片的文件名,在ios,android手机,谷歌浏览器测试,上传下载没有问题。

2、测试的html的核心代码如下,进行图片的上传和下载:

<!DOCTYPE html>
<html> 

 <head>
 <meta charset="UTF-8" />
 <title>websocket chat</title>
 </head> 

 <body> 

 <div>
  <label>输入信息:</label><input id="id" width="100px" /><br />
  <button id="btn">发送消息</button>
  <button id="connection">websocket连接</button>
  <button id="disconnection">断开websocket连接</button>
  <br /><br />
  <form enctype="multipart/form-data" id="uploadForm">
  <input type="file" name="uploadFile" id="upload_file" style="margin-bottom:10px;">
  <input type="button" id="uploadPicButton" value="上传" onclick="uploadImage()">
  </form>
  <!--<input type="file" onchange="uploadImgTest();" id="uploadImg" name="uploadImg" />
  <button id="uploadImage" onclick="uploadImage();">上传</button>-->
 </div> 

 <div id="test"> 

 </div> 

 <hr color="blanchedalmond"/>
 <div id="voiceDiv"> 

 </div> 

 <hr color="chartreuse" />
 <div id="imgDiv" style="width: 30%;height: 30%;">
  <img src="http://192.168.9.123:8860/v1/uploadDownload/downloadImage?imageName=123.JPG" style="width: 160px;height: 160px;"/>
 </div> 

</body> 

 <script src="js/jquery-3.2.1.min.js"></script>
 <!--<script th:src="@{stomp.min.js}"></script>-->
 <script src="js/sockjs.min.js"></script> 

 <script>
 var websocketUrl = "ws://192.168.9.123:8860/webSocketServer";
 var websocket;
 if('WebSocket' in window) {
  //websocket = new WebSocket("ws://" + document.location.host + "/webSocketServer");
  //websocket = new WebSocket("ws://192.168.9.123:9092/webSocketServer");
  //websocket = new WebSocket("ws://localhost:8860/webSocketServer");
  websocket = new WebSocket(websocketUrl);
 } else if('MozWebSocket' in window) {
  websocket = new MozWebSocket("ws://" + document.location.host + "/webSocketServer");
 } else {
  websocket = new SockJS("http://" + document.location.host + "/sockjs/webSocketServer");
 }
 websocket.onopen = function(evnt) {
  console.log("onopen----", evnt.data);
 };
 websocket.onmessage = function(evnt) {
  //$("#test").html("(<font color='red'>" + evnt.data + "</font>)");
  console.log("onmessage----", evnt.data);
  //$("#test").html(evnt.data);
  $("#test").append('<div>' + event.data + '</div>');
 };
 websocket.onerror = function(evnt) {
  console.log("onerror----", evnt.data);
 }
 websocket.onclose = function(evnt) {
  console.log("onclose----", evnt.data);
 }
 $('#btn').on('click', function() {
  if(websocket.readyState == websocket.OPEN) {
  var msg = $('#id').val();
  //调用后台handleTextMessage方法
  websocket.send(msg);
  } else {
  alert("连接失败!");
  }
 });
 $('#disconnection').on('click', function() {
  if(websocket.readyState == websocket.OPEN) {
  websocket.close();
  //websocket.onclose();
  console.log("关闭websocket连接成功");
  }
 });
 $('#connection').on('click', function() {
  if(websocket.readyState == websocket.CLOSED) {
  websocket.open();
  //websocket.onclose();
  console.log("打开websocket连接成功");
  }
 });
 //监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
 window.onbeforeunload = function() {
  websocket.close();
 } 

 function uploadImgTest() { 

 } 

 function uploadImage(){
  //var uploadUrl = "http://localhost:8860/v1/uploadDownload/uploadImage";
 var uploadUrl = "http://192.168.9.123:8860/v1/uploadDownload/uploadImage";
 var downUrl = "http://192.168.9.123:8860/v1/uploadDownload/downloadImage"
 var pic = $('#upload_file')[0].files[0];
 var fd = new FormData();
 //fd.append('uploadFile', pic);
 fd.append('file', pic);
 $.ajax({
  url:uploadUrl,
  type:"post",
  // Form数据
  data: fd,
  cache: false,
  contentType: false,
  processData: false,
  success:function(data){
  console.log("the data is : {}",data);
  if(data.code == 0){
   console.log("上传成功后的文件路径为:"+data.data);
   var img = $("<img />")
   img.attr("src",downUrl+"?imageName="+data.data);
   img.width("160px");
   img.height("160px");
   $("#imgDiv").append(img);
  } 

  }
 }); 

 } 

 </script> 

</html>

上面的代码有些和图片的上传和下载没有关系,根据需要自己去掉,看图片上传和下载的核心代码,需要引入jquery。

3、spring boot的属性配置:

1.解决图片上传太大的问题:

spring:
 http:
 multipart:
 max-file-size: 100Mb #文件上传大小
 max-request-size: 200Mb #最打请求大小

这是新版spring boot解决图片或者文件上传太大的问题,老板的不是这样解决的。可以自己查资料

2.配置文件上传保存的位置:

#上传位置
uploadDir: F:\mystudy\pic\

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

元宵节福利:

您可能感兴趣的文章:

  • 详解SpringBoot文件上传下载和多文件上传(图文)
  • Spring Boot实现图片上传功能
  • spring boot 图片上传与显示功能实例详解
  • Spring Boot实现文件上传示例代码
  • spring MVC + bootstrap实现文件上传示例(带进度条)
  • springboot实现文件上传和下载功能
  • Spring boot实现文件上传实例(多文件上传)
  • SpringBoot实现文件上传下载功能小结
  • spring boot实现上传图片并在页面上显示及遇到的问题小结
  • 基于SpringBoot上传任意文件功能的实现
(0)

相关推荐

  • SpringBoot实现文件上传下载功能小结

    最近做的一个项目涉及到文件上传与下载.前端上传采用百度webUploader插件.有关该插件的使用方法还在研究中,日后整理再记录.本文主要介绍SpringBoot后台对文件上传与下载的处理. 单文件上传 // 单文件上传 @RequestMapping(value = "/upload") @ResponseBody public String upload(@RequestParam("file") MultipartFile file) { try { if (

  • Spring boot实现文件上传实例(多文件上传)

    文件上传主要分以下几个步骤: (1)新建maven java project: (2)在pom.xml加入相应依赖: (3)新建一个表单页面(这里使用thymleaf); (4)编写controller; (5)测试: (6)对上传的文件做一些限制: (7)多文件上传实现 (1)新建maven Java project 新建一个名称为spring-boot-fileupload maven Java项目: (2)在pom.xml加入相应依赖: 加入相应的maven依赖,具体看以下解释: <pro

  • 基于SpringBoot上传任意文件功能的实现

    一.pom文件依赖的添加 <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</gr

  • spring boot实现上传图片并在页面上显示及遇到的问题小结

    最近在使用spring boot搭建网站的过程之中遇到了这样一个问题:用户注册时需要上传一个属于自己的头像,注册成功之后跳转到个人中心,在个人中心中显示用户信息.其中在显示头像的时候遇到了问题:上传头像的时候,我把头像存放到了项目文件下的static文件夹中,将其地址存放到了数据库对应的用户中,并且在idea中添加了热部署,但是在注册跳转到个人中心后还是无法显示头像,只有在下一次启动项目进入到个人中心时才可以. 被这个问题困扰了许久,最后是这样的解决的:在main目录下新建了一个webapp文件

  • Spring Boot实现图片上传功能

    本文实例为大家分享了Spring Boot图片上传的具体代码,供大家参考,具体内容如下 package com.clou.inteface.domain.web.user; import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.Map; import org.apache.commons.lang3.StringUtils; import org.springfram

  • Spring Boot实现文件上传示例代码

    使用SpringBoot进行文件上传的方法和SpringMVC差不多,本文单独新建一个最简单的DEMO来说明一下. 主要步骤包括: 1.创建一个springboot项目工程,本例名称(demo-uploadfile). 2.配置 pom.xml 依赖. 3.创建和编写文件上传的 Controller(包含单文件上传和多文件上传). 4.创建和编写文件上传的 HTML 测试页面. 5.文件上传相关限制的配置(可选). 6.运行测试. 项目工程截图如下: 文件代码: <dependencies>

  • spring MVC + bootstrap实现文件上传示例(带进度条)

    最近学习了bootstrap,有结合了spring MVC写了个文件上传的示例,留做笔记,废话不多说,直接上代码 监听器类FileUploadProgressListener.Java package com.gpl.web.listener; import javax.servlet.http.HttpSession; import org.apache.commons.fileupload.ProgressListener; import org.springframework.stereo

  • springboot实现文件上传和下载功能

    spring boot 引入"约定大于配置"的概念,实现自动配置,节约了开发人员的开发成本,并且凭借其微服务架构的方式和较少的配置,一出来就占据大片开发人员的芳心.大部分的配置从开发人员可见变成了相对透明了,要想进一步熟悉还需要关注源码. 1.文件上传(前端页面): <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/lo

  • spring boot 图片上传与显示功能实例详解

    首先描述一下问题,spring boot 使用的是内嵌的tomcat, 所以不清楚文件上传到哪里去了, 而且spring boot 把静态的文件全部在启动的时候都会加载到classpath的目录下的,所以上传的文件不知相对于应用目录在哪,也不知怎么写访问路径合适,对于新手的自己真的一头雾水. 后面想起了官方的例子,没想到一开始被自己找到的官方例子,后面太依赖百度谷歌了,结果发现只有官方的例子能帮上忙,而且帮上大忙,直接上密码的代码 package hello; import static org

  • 详解SpringBoot文件上传下载和多文件上传(图文)

    最近在学习SpringBoot,以下是最近学习整理的实现文件上传下载的Java代码: 1.开发环境: IDEA15+ Maven+JDK1.8 2.新建一个maven工程: 3.工程框架 4.pom.xml文件依赖项 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation

随机推荐