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

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

 1,核心的controller代码


  
  
  1. package com.qwrt.station.websocket.controller;
  2. import com.alibaba.fastjson.JSONObject;
  3. import com.qwrt.station.common.util.JsonUtil;
  4. import org.slf4j.Logger;
  5. import org.slf4j.LoggerFactory;
  6. import org.springframework.beans.factory.annotation.Value;
  7. import org.springframework.web.bind.annotation.RequestMapping;
  8. import org.springframework.web.bind.annotation.RequestMethod;
  9. import org.springframework.web.bind.annotation.RequestParam;
  10. import org.springframework.web.bind.annotation.RestController;
  11. import org.springframework.web.multipart.MultipartFile;
  12. import javax.servlet.http.HttpServletRequest;
  13. import javax.servlet.http.HttpServletResponse;
  14. import java.io.*;
  15. /**
  16. * Created by jack on 2017/10/30.
  17. */
  18. @RestController
  19. @RequestMapping( "v1/uploadDownload")
  20. public class UploadDownloadController {
  21. private static final Logger logger = LoggerFactory.getLogger(UploadDownloadController.class);
  22. @Value( "${uploadDir}")
  23. private String uploadDir;
  24. @RequestMapping(value = "/uploadImage", method = RequestMethod.POST)
  25. public JSONObject uploadImage(@RequestParam(value = "file") MultipartFile file) throws RuntimeException {
  26. if (file.isEmpty()) {
  27. return JsonUtil.getFailJsonObject( "文件不能为空");
  28. }
  29. // 获取文件名
  30. String fileName = file.getOriginalFilename();
  31. logger.info( "上传的文件名为:" + fileName);
  32. // 获取文件的后缀名
  33. String suffixName = fileName.substring(fileName.lastIndexOf( "."));
  34. logger.info( "上传的后缀名为:" + suffixName);
  35. // 文件上传后的路径
  36. String filePath = uploadDir;
  37. // 解决中文问题,liunx下中文路径,图片显示问题
  38. // fileName = UUID.randomUUID() + suffixName;
  39. File dest = new File(filePath + fileName);
  40. // 检测是否存在目录
  41. if (!dest.getParentFile().exists()) {
  42. dest.getParentFile().mkdirs();
  43. }
  44. try {
  45. file.transferTo(dest);
  46. logger.info( "上传成功后的文件路径未:" + filePath + fileName);
  47. return JsonUtil.getSuccessJsonObject(fileName);
  48. } catch (IllegalStateException e) {
  49. e.printStackTrace();
  50. } catch (IOException e) {
  51. e.printStackTrace();
  52. }
  53. return JsonUtil.getFailJsonObject( "文件上传失败");
  54. }
  55. //文件下载相关代码
  56. @RequestMapping(value = "/downloadImage",method = RequestMethod.GET)
  57. public String downloadImage(String imageName,HttpServletRequest request, HttpServletResponse response) {
  58. //String fileName = "123.JPG";
  59. logger.debug( "the imageName is : "+imageName);
  60. String fileUrl = uploadDir+imageName;
  61. if (fileUrl != null) {
  62. //当前是从该工程的WEB-INF//File//下获取文件(该目录可以在下面一行代码配置)然后下载到C:\\users\\downloads即本机的默认下载的目录
  63. /* String realPath = request.getServletContext().getRealPath(
  64. "//WEB-INF//");*/
  65. /*File file = new File(realPath, fileName);*/
  66. File file = new File(fileUrl);
  67. if (file.exists()) {
  68. response.setContentType( "application/force-download"); // 设置强制下载不打开
  69. response.addHeader( "Content-Disposition",
  70. "attachment;fileName=" + imageName); // 设置文件名
  71. byte[] buffer = new byte[ 1024];
  72. FileInputStream fis = null;
  73. BufferedInputStream bis = null;
  74. try {
  75. fis = new FileInputStream(file);
  76. bis = new BufferedInputStream(fis);
  77. OutputStream os = response.getOutputStream();
  78. int i = bis.read(buffer);
  79. while (i != - 1) {
  80. os.write(buffer, 0, i);
  81. i = bis.read(buffer);
  82. }
  83. System.out.println( "success");
  84. } catch (Exception e) {
  85. e.printStackTrace();
  86. } finally {
  87. if (bis != null) {
  88. try {
  89. bis.close();
  90. } catch (IOException e) {
  91. e.printStackTrace();
  92. }
  93. }
  94. if (fis != null) {
  95. try {
  96. fis.close();
  97. } catch (IOException e) {
  98. e.printStackTrace();
  99. }
  100. }
  101. }
  102. }
  103. }
  104. return null;
  105. }
  106. }

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


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


  
  
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="UTF-8" />
  5. <title>websocket chat </title>
  6. </head>
  7. <body>
  8. <div>
  9. <label>输入信息: </label> <input id="id" width="100px" /> <br />
  10. <button id="btn">发送消息 </button>    
  11. <button id="connection">websocket连接 </button>     
  12. <button id="disconnection">断开websocket连接 </button>
  13. <br /> <br />
  14. <form enctype="multipart/form-data" id="uploadForm">
  15. <input type="file" name="uploadFile" id="upload_file" style="margin-bottom:10px;">
  16. <input type="button" id="uploadPicButton" value="上传" onclick="uploadImage()">
  17. </form>
  18. <!--<input type="file" οnchange="uploadImgTest();" id="uploadImg" name="uploadImg" />
  19. <button id="uploadImage" οnclick="uploadImage();">上传</button>-->
  20. </div>
  21. <div id="test">
  22. </div>
  23. <hr color="blanchedalmond"/>
  24. <div id="voiceDiv">
  25. </div>
  26. <hr color="chartreuse" />
  27. <div id="imgDiv" style="width: 30%;height: 30%;">
  28. <img src="http://192.168.9.123:8860/v1/uploadDownload/downloadImage?imageName=123.JPG" style="width: 160px;height: 160px;"/>
  29. </div>
  30. </body>
  31. <script src="js/jquery-3.2.1.min.js"> </script>
  32. <!--<script th:src="@{stomp.min.js}"></script>-->
  33. <script src="js/sockjs.min.js"> </script>
  34. <script>
  35. var websocketUrl = "ws://192.168.9.123:8860/webSocketServer";
  36. var websocket;
  37. if( 'WebSocket' in window) {
  38. //websocket = new WebSocket("ws://" + document.location.host + "/webSocketServer");
  39. //websocket = new WebSocket("ws://192.168.9.123:9092/webSocketServer");
  40. //websocket = new WebSocket("ws://localhost:8860/webSocketServer");
  41. websocket = new WebSocket(websocketUrl);
  42. } else if( 'MozWebSocket' in window) {
  43. websocket = new MozWebSocket( "ws://" + document.location.host + "/webSocketServer");
  44. } else {
  45. websocket = new SockJS( "http://" + document.location.host + "/sockjs/webSocketServer");
  46. }
  47. websocket.onopen = function(evnt) {
  48. console.log( "onopen----", evnt.data);
  49. };
  50. websocket.onmessage = function(evnt) {
  51. //$("#test").html("(<font color='red'>" + evnt.data + "</font>)");
  52. console.log( "onmessage----", evnt.data);
  53. //$("#test").html(evnt.data);
  54. $( "#test").append( '<div>' + event.data + '</div>');
  55. };
  56. websocket.onerror = function(evnt) {
  57. console.log( "onerror----", evnt.data);
  58. }
  59. websocket.onclose = function(evnt) {
  60. console.log( "onclose----", evnt.data);
  61. }
  62. $( '#btn').on( 'click', function() {
  63. if(websocket.readyState == websocket.OPEN) {
  64. var msg = $( '#id').val();
  65. //调用后台handleTextMessage方法
  66. websocket.send(msg);
  67. } else {
  68. alert( "连接失败!");
  69. }
  70. });
  71. $( '#disconnection').on( 'click', function() {
  72. if(websocket.readyState == websocket.OPEN) {
  73. websocket.close();
  74. //websocket.onclose();
  75. console.log( "关闭websocket连接成功");
  76. }
  77. });
  78. $( '#connection').on( 'click', function() {
  79. if(websocket.readyState == websocket.CLOSED) {
  80. websocket.open();
  81. //websocket.onclose();
  82. console.log( "打开websocket连接成功");
  83. }
  84. });
  85. //监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
  86. window.onbeforeunload = function() {
  87. websocket.close();
  88. }
  89. function uploadImgTest() {
  90. }
  91. function uploadImage(){
  92. //var uploadUrl = "http://localhost:8860/v1/uploadDownload/uploadImage";
  93. var uploadUrl = "http://192.168.9.123:8860/v1/uploadDownload/uploadImage";
  94. var downUrl = "http://192.168.9.123:8860/v1/uploadDownload/downloadImage"
  95. var pic = $( '#upload_file')[ 0].files[ 0];
  96. var fd = new FormData();
  97. //fd.append('uploadFile', pic);
  98. fd.append( 'file', pic);
  99. $.ajax({
  100. url:uploadUrl,
  101. type: "post",
  102. // Form数据
  103. data: fd,
  104. cache: false,
  105. contentType: false,
  106. processData: false,
  107. success: function(data){
  108. console.log( "the data is : {}",data);
  109. if(data.code == 0){
  110. console.log( "上传成功后的文件路径为:"+data.data);
  111. var img = $( "<img />")
  112. img.attr( "src",downUrl+ "?imageName="+data.data);
  113. img.width( "160px");
  114. img.height( "160px");
  115. $( "#imgDiv").append(img);
  116. }
  117. }
  118. });
  119. }
  120. </script>
  121. </html>

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


3,spring boot的属性配置:

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


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

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

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

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



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


spring boot多文件上传:

核心代码:


  
  
  1. /**
  2. * 多文件上传
  3. * @param files
  4. * @return
  5. * @throws RuntimeException
  6. */
  7. @RequestMapping(value = "/uploadFiles", method = RequestMethod.POST)
  8. public JSONObject uploadFiles(@RequestParam(value = "file") MultipartFile[] files){
  9. StringBuffer result = new StringBuffer();
  10. try {
  11. for ( int i = 0; i < files.length; i++) {
  12. if (files[i] != null) {
  13. //调用上传方法
  14. String fileName = executeUpload(files[i]);
  15. result.append(fileName+ ";");
  16. }
  17. }
  18. } catch (Exception e) {
  19. e.printStackTrace();
  20. JsonUtil.getFailJsonObject( "文件上传失败");
  21. }
  22. return JsonUtil.getSuccessJsonObject(result.toString());
  23. }
  24. /**
  25. * 提取上传方法为公共方法
  26. * @param file
  27. * @return
  28. * @throws Exception
  29. */
  30. private String executeUpload(MultipartFile file)throws Exception{
  31. //文件后缀名
  32. String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf( "."));
  33. //上传文件名
  34. String fileName = UUID.randomUUID()+suffix;
  35. //服务端保存的文件对象
  36. File serverFile = new File(uploadDir + fileName);
  37. // 检测是否存在目录
  38. if (!serverFile.getParentFile().exists()) {
  39. serverFile.getParentFile().mkdirs();
  40. }
  41. //将上传的文件写入到服务器端文件内
  42. file.transferTo(serverFile);
  43. return fileName;
  44. }




  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值