Springboot上传图片到nginx
程序员文章站
2022-05-17 08:55:26
...
springbot上传图片到本地和springmvc的类似,此处不再做介绍。可以参考:https://blog.csdn.net/duan196_118/article/details/103836831
本次介绍上传图片到nginx服务器。
1.编写连接Linux的配置文件,linux.properties
# 账号
linux.username=root
# 密码
linux.password=root
# ip路径
linux.ip=192.168.xx.xx
# nginx端口
linux.port=8089
# 虚拟机端口号
linux.id=22
# 上传根目录
linux.uploadPath=/home/accessory
# 文件上传访问路径
linux.downPath=/accessory/
2.在application.properties中添加文件上传的配置
#文件上传
multipart.maxFileSize=500Mb
multipart.maxRequestSize=500Mb
3.编写工具类Sftp.java
package com.dsx.util;
import java.io.InputStream;
import java.util.Properties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException;
/**
*
* @ClassName: SFTP
* @Description: sftp连接工具类
* @date 2019年11月25日 下午10:00:00
* @version 1.0.0
*/
public class Sftp {
private transient Logger log = LoggerFactory.getLogger(this.getClass());
private ChannelSftp sftp;
private Session session;
/** FTP 登录用户名 */
private String username;
/** FTP 登录密码 */
private String password;
/** 私钥 */
private String privateKey;
/** FTP 服务器地址IP地址 */
private String host;
/** FTP 端口 */
private int port;
/**
* 构造基于密码认证的sftp对象
*
* @param userName
* @param password
* @param host
* @param port
*/
public Sftp(String username, String password, String host, int port) {
this.username = username;
this.password = password;
this.host = host;
this.port = port;
}
/**
* 构造基于秘钥认证的sftp对象
*
* @param userName
* @param host
* @param port
* @param privateKey
*/
public Sftp(String username, String host, int port, String privateKey) {
this.username = username;
this.host = host;
this.port = port;
this.privateKey = privateKey;
}
public Sftp() {
}
/**
* 连接sftp服务器
*
* @throws Exception
*/
public void login() {
try {
JSch jsch = new JSch();
if (privateKey != null) {
jsch.addIdentity(privateKey);// 设置私钥
log.info("sftp connect,path of private key file:{}", privateKey);
}
log.info("sftp connect by host:{} username:{}", host, username);
session = jsch.getSession(username, host, port);
log.info("Session is build");
if (password != null) {
session.setPassword(password);
}
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
log.info("Session is connected");
Channel channel = session.openChannel("sftp");
channel.connect();
log.info("channel is connected");
sftp = (ChannelSftp) channel;
log.info(String.format("sftp server host:[%s] port:[%s] is connect successfull", host, port));
} catch (JSchException e) {
log.error("Cannot connect to specified sftp server : {}:{} \n Exception message is: {}",
new Object[] { host, port, e.getMessage() });
}
}
/**
* 关闭连接 server
*/
public void logout() {
if (sftp != null) {
if (sftp.isConnected()) {
sftp.disconnect();
log.info("sftp is closed already");
}
}
if (session != null) {
if (session.isConnected()) {
session.disconnect();
log.info("sshSession is closed already");
}
}
}
/**
* 将输入流的数据上传到sftp作为文件
*
* @param directory 上传到该目录
* @param sftpFileName sftp端文件名
* @param in 输入流
* @throws SftpException
* @throws Exception
*/
public void upload(String directory, String sftpFileName, InputStream input) throws SftpException {
try {
sftp.cd(directory);
} catch (SftpException e) {
log.warn("directory is not exist");
sftp.mkdir(directory);
sftp.cd(directory);
}
sftp.put(input, sftpFileName);
log.info("file:{} is upload successful", sftpFileName);
}
}
4.编写测试代码
package com.dsx.controller;
import java.io.IOException;
import java.util.HashMap;
import java.util.Properties;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import com.dsx.util.Sftp;
/**
*
* @ClassName: UploadLinuxController
* @Description: 测试上传到nginx
* @author 曰业而安
*
*/
@Controller
public class UploadLinuxController {
private static Properties linuxProperties = new Properties();
public static String USERNAME;
public static String PASSWORD;
public static String IP;
public static Integer ID;
public static String UPLOAD_PATH;
public static String DOWN_PATH;
public static String PORT;
static{
//获取连接linux连接信息
try {
linuxProperties.load(UploadLinuxController.class.getClassLoader().getResourceAsStream("config/linux.properties"));
} catch (IOException e) {
e.printStackTrace();
}
USERNAME = linuxProperties.getProperty("linux.username");
PASSWORD = linuxProperties.getProperty("linux.password");
IP = linuxProperties.getProperty("linux.ip");
ID = Integer.valueOf(linuxProperties.getProperty("linux.id"));
UPLOAD_PATH = linuxProperties.getProperty("linux.uploadPath");
DOWN_PATH = linuxProperties.getProperty("linux.downPath");
PORT = linuxProperties.getProperty("linux.port");
}
@RequestMapping("/uploadPageLinux")
public String uploadPage() {
return "/WEB-INF/views/html/uploadLinux.html";
}
@RequestMapping("/upload")
@ResponseBody
public HashMap<String, Object> upload(MultipartFile file,HttpServletRequest request) {
System.err.println("前台获取的值 file"+file);
String savePath=null;
HashMap<String, Object> map = new HashMap<String,Object>();
//实例化工具类,填写用户名,密码,ip地址,端口号,用来连接linux
Sftp sftpUtil = new Sftp(USERNAME, PASSWORD, IP, ID);
//连接服务器
sftpUtil.login();
try {
String filename = file.getOriginalFilename();
System.err.println("图片名称"+filename);
//保存的文件的名称
String name=UUID.randomUUID().toString().replace("-", "")+filename.substring(filename.lastIndexOf("."));
System.out.println(UPLOAD_PATH+"====上传地址===");
sftpUtil.upload(UPLOAD_PATH, name, file.getInputStream());
//图片在nginx中的位置
savePath=DOWN_PATH+name;
map.put("code", 200);
map.put("src", savePath);
} catch (Exception e) {
System.out.println("上传失败。。。。。");
map.put("code", 400);
e.printStackTrace();
}finally {
//释放连接
sftpUtil.logout();
}
return map;
}
}
5.html页面
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>文件上传</title>
<script type="text/javascript" src="/static/js/jquery-1.8.3.js"></script>
<script type="text/javascript" src="/static/js/jquery.form.js"></script>
</head>
<body>
<form action="" method="post" enctype="multipart/form-data" id="form">
<input type="file" name="file" onchange="changeImg()"><br>
<img src="" id="img">
<input type="hidden" id="img_url">
<input type="button" value="上传">
</form>
<script type="text/javascript">
function changeImg(){
var options ={
url:'/upload',
method:'POST',
dataType:'json',
success:function(data){
console.log(data);
alert(data.code);
if(data.code == 200){
$("#img_url").val(data.src);
//访问nginx中图片的路径进行回显
$("#img").attr("src","http://192.168.20.88:8089/"+data.src);
}
}
}
$("#form").ajaxSubmit(options);
}
</script>
</body>
</html>
6. nginx中相关的配置
在实际的业务场景中,由于客户端可能没有进行上传图片的操作,所以在上传图片的逻辑代码中可以对参数file进行非空判断。使业务逻辑更加严谨,同时避免了不必要的bug。欢迎留言指正。
下一篇: java自定义注解实现多数据源切换