springboot实现图⽚上传和下载功能
这篇博客简单介绍下spring boot下图⽚上传和下载,已经遇到的问题。⾸先需要创建⼀个spring boot项⽬。
1、核⼼的controller代码
package com.qwrt.ller;
import com.alibaba.fastjson.JSONObject;
import com.qwrt.stationmon.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;函数if在excel中怎么操作
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 = Logger(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()) {
FailJsonObject("⽂件不能为空");
}
// 获取⽂件名
String fileName = OriginalFilename();
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 (!ParentFile().exists()) {
}
try {
logger.info("上传成功后的⽂件路径未:" + filePath + fileName);
SuccessJsonObject(fileName);
} catch (IllegalStateException e) {
e.printStackTrace();
超市管理系统数据库设计报告} catch (IOException e) {
e.printStackTrace();
}
FailJsonObject("⽂件上传失败");
}
//⽂件下载相关代码
@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 = ServletContext().getR
ealPath(
"//WEB-INF//");*/
/*File file = new File(realPath, fileName);*/
File file = new File(fileUrl);
if (ists()) {
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 = OutputStream();指数函数的运算法则与公式
int i = ad(buffer);
while (i != -1) {
os.write(buffer, 0, i);
i = ad(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>
8a8a80c怎么观看<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" >
<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">jquery下载文件请求
</div>
<hr color="chartreuse" />
<div id="imgDiv" >
<img src="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("" + document.location.host + "/sockjs/webSocketServer");
}
console.log("onopen----", evnt.data);
};
//$("#test").html("(<font color='red'>" + evnt.data + "</font>)");
console.log("onmessage----", evnt.data);
//$("#test").html(evnt.data);
$("#test").append('<div>' + event.data + '</div>');
};
console.log("onerror----", evnt.data);
}
console.log("onclose----", evnt.data);
}
$('#btn').on('click', function() {
adyState == websocket.OPEN) {
var msg = $('#id').val();
//调⽤后台handleTextMessage⽅法
websocket.send(msg);
} else {
alert("连接失败!");
}
});
$('#disconnection').on('click', function() {
adyState == websocket.OPEN) {
websocket.close();
//lose();
console.log("关闭websocket连接成功");
}
});
$('#connection').on('click', function() {
adyState == websocket.CLOSED) {
websocket.open();
//lose();
console.log("打开websocket连接成功");
}
});
//监听窗⼝关闭事件,当窗⼝关闭时,主动去关闭websocket连接,防⽌连接还没断开就关闭窗⼝,server端会抛异常。
websocket.close();
}
function uploadImgTest() {
}
function uploadImage(){
//var uploadUrl = "localhost:8860/v1/uploadDownload/uploadImage";
var uploadUrl = "192.168.9.123:8860/v1/uploadDownload/uploadImage";
var downUrl = "192.168.9.123:8860/v1/uploadDownload/downloadImage"
var pic = $('#upload_file')[0].files[0];js加密算法
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);
de == 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\
以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。
元宵节福利:
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论