欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-06-14 23:34:51
 这篇博客简单介绍下spring boot下图片上传和下载,已经遇到的问题。首先需要创建一个spring boot项目。 1、核心的controller代码...

 这篇博客简单介绍下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\

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

元宵节福利:

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