This blog briefly introduces the problems you have encountered when uploading and downloading pictures under spring boot. First, you need to create a spring boot project.
1. The core controller code
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("The file cannot be empty"); } // Get the file name String fileName = file.getOriginalFilename(); logger.info("The uploaded file name is: " + fileName); // Get the file suffixName = fileName.substring(fileName.lastIndexOf(".")); logger.info("The uploaded suffixname is: " + suffixName); // The path after file upload String filePath = uploadDir; // Solve Chinese problems, Chinese path under liunx, picture display problem // fileName = UUID.randomUUID() + suffixName; File dest = new File(filePath + fileName); // Detect whether the directory exists if (!dest.getParentFile().exists()) { dest.getParentFile().mkdirs(); } try { file.transferTo(dest); logger.info("The file path after uploading is not: " + filePath + fileName); return JsonUtil.getSuccessJsonObject(fileName); } catch (IllegalStateException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return JsonUtil.getFailJsonObject("File upload failed"); } //File download related code @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) { //Currently, the file is obtained from the WEB-INF//File// of the project (this directory can be configured in the following line of code) and download to C://users//downloads, which is the default download directory of the machine/* 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");// Set the forced download not to open response.addHeader("Content-Disposition", "attachment;fileName=" + imageName);// Set the file name 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; } } } }There are two methods in the above code. The above method is the method of uploading images, and the following method is the method of downloading images. To download the image, you need to pass the file name of the image. Test it on iOS, Android phone, Google Chrome, and there is no problem uploading and downloading.
2. The core code of the tested html is as follows, upload and download pictures:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <title>websocket chat</title> </head> <body> <div> <label>Input information: </label><input id="id" /><br /> <button id="btn">Send a message</button> <button id="connection">websocket connection</button> <button id="disconnection">Disconnection</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="upload" onclick="uploadImage()"> </form> <!--<input type="file" onchange="uploadImgTest();" id="uploadImg" name="uploadImg" /> <button id="uploadImage" onclick="uploadImage();">Upload</button>--> </div> <div id="test"> </div> <hr color="blanchedalmond"/> <div id="voiceDiv"> </div> <hr color="chartreuse" /> <div id="imgDiv"> <img src="http://192.168.9.123:8860/v1/uploadDownload/downloadImage?imageName=123.JPG"/> </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(); //Calculating the background handleTextMessage method websocket.send(msg); } else { alert("Connection failed!"); } }); $('#disconnection').on('click', function() { if(websocket.readyState == websocket.OPEN) { websocket.close(); //websocket.onclose(); console.log("Close the websocket connection successfully"); } }); $('#connection').on('click', function() { if(websocket.readyState == websocket.CLOSED) { websocket.open(); //websocket.onclose(); console.log("open the websocket connection successfully"); } }); // Listen to the window closing event. When the window is closed, actively close the websocket connection to prevent the window from closing before the connection is disconnected, and the server side will throw exceptions. 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 downloadUrl = "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 data: fd, cache: false, contentType: false, processData: false, success:function(data){ console.log("the data is : {}",data); if(data.code == 0){ console.log("The file path after uploading is: "+data.data); var img = $("<img />") img.attr("src",downUrl+"?imageName="+data.data); img.width("160px"); img.height("160px"); $("#imgDiv").append(img); } } }); } </script> </html>Some of the above codes have nothing to do with uploading and downloading pictures. Remove them yourself as needed and look at the core code for uploading and downloading pictures. You need to introduce jquery.
3. Spring boot property configuration:
1. Solve the problem of too big picture upload:
spring: http: multipart: max-file-size: 100Mb #file upload size max-request-size: 200Mb #maximum request size
This is the new version of spring boot to solve the problem of too big upload of pictures or files. This is not how the boss solved it. You can check the information yourself
2. The location where the configuration file is uploaded and saved:
#UploadDir: F:/mystudy/pic/
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.
Lantern Festival Welfare: