使用springboot怎么實(shí)現(xiàn)圖片上傳和下載功能

今天就跟大家聊聊有關(guān)使用spring boot怎么實(shí)現(xiàn)圖片上傳和下載功能,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結(jié)了以下內(nèi)容,希望大家根據(jù)這篇文章可以有所收獲。

建網(wǎng)站原本是網(wǎng)站策劃師、網(wǎng)絡(luò)程序員、網(wǎng)頁設(shè)計(jì)師等,應(yīng)用各種網(wǎng)絡(luò)程序開發(fā)技術(shù)和網(wǎng)頁設(shè)計(jì)技術(shù)配合操作的協(xié)同工作。成都創(chuàng)新互聯(lián)專業(yè)提供網(wǎng)站設(shè)計(jì)制作、成都網(wǎng)站建設(shè),網(wǎng)頁設(shè)計(jì),網(wǎng)站制作(企業(yè)站、響應(yīng)式網(wǎng)站、電商門戶網(wǎng)站)等服務(wù),從網(wǎng)站深度策劃、搜索引擎友好度優(yōu)化到用戶體驗(yàn)的提升,我們力求做到極致!

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("文件上傳失敗"); 
 } 
 
 //文件下載相關(guān)代碼 
 @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) { 
  //當(dāng)前是從該工程的WEB-INF//File//下獲取文件(該目錄可以在下面一行代碼配置)然后下載到C:\\users\\downloads即本機(jī)的默認(rèn)下載的目錄 
  /* 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");// 設(shè)置強(qiáng)制下載不打開 
  response.addHeader("Content-Disposition", 
   "attachment;fileName=" + imageName);// 設(shè)置文件名 
  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; 
 } 
 
 
}

     上面的代碼有兩個(gè)方法,上面的方法是圖片上傳的方法,下面的方法是圖片下載的方法。下載圖片需要傳入圖片的文件名,在ios,android手機(jī),谷歌瀏覽器測試,上傳下載沒有問題。

2、測試的html的核心代碼如下,進(jìn)行圖片的上傳和下載:

<!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">發(fā)送消息</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" > 
  <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" > 
  <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(); 
  //調(diào)用后臺(tái)handleTextMessage方法 
  websocket.send(msg); 
  } else { 
  alert("連接失敗!"); 
  } 
 }); 
 $('#disconnection').on('click', function() { 
  if(websocket.readyState == websocket.OPEN) { 
  websocket.close(); 
  //websocket.onclose(); 
  console.log("關(guān)閉websocket連接成功"); 
  } 
 }); 
 $('#connection').on('click', function() { 
  if(websocket.readyState == websocket.CLOSED) { 
  websocket.open(); 
  //websocket.onclose(); 
  console.log("打開websocket連接成功"); 
  } 
 }); 
 //監(jiān)聽窗口關(guān)閉事件,當(dāng)窗口關(guān)閉時(shí),主動(dòng)去關(guān)閉websocket連接,防止連接還沒斷開就關(guān)閉窗口,server端會(huì)拋異常。 
 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數(shù)據(jù) 
  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>

上面的代碼有些和圖片的上傳和下載沒有關(guān)系,根據(jù)需要自己去掉,看圖片上傳和下載的核心代碼,需要引入jquery。

3、spring boot的屬性配置:

1.解決圖片上傳太大的問題:

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

這是新版spring boot解決圖片或者文件上傳太大的問題,老板的不是這樣解決的。可以自己查資料

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

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

springboot是什么

springboot一種全新的編程規(guī)范,其設(shè)計(jì)目的是用來簡化新Spring應(yīng)用的初始搭建以及開發(fā)過程,SpringBoot也是一個(gè)服務(wù)于框架的框架,服務(wù)范圍是簡化配置文件。

看完上述內(nèi)容,你們對使用spring boot怎么實(shí)現(xiàn)圖片上傳和下載功能有進(jìn)一步的了解嗎?如果還想了解更多知識(shí)或者相關(guān)內(nèi)容,請關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝大家的支持。

網(wǎng)頁標(biāo)題:使用springboot怎么實(shí)現(xiàn)圖片上傳和下載功能
瀏覽地址:http://muchs.cn/article6/phoiig.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供自適應(yīng)網(wǎng)站、網(wǎng)站策劃、云服務(wù)器、手機(jī)網(wǎng)站建設(shè)、響應(yīng)式網(wǎng)站網(wǎng)站導(dǎo)航

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)

成都定制網(wǎng)站建設(shè)