图片上传?本地?服务器?
2019-12-04 本文已影响0人
HeloWxl
最近的做的一个项目,就是将图片上传到服务器上去,so....。
- 声明一下哈:我这里是写的一个demo,将上传的代码是直接写在了Controller。在实际的项目中的,应该是写在service里面的,大家千万不要学我。
1、将文件上传到本地
1.1uploadToLocal.jsp
//省略引入layui.css+layui.js
<div class="grid-demo">
<div class="layui-upload" style="text-align: center">
上传图片
<div class="layui-upload-list">
<img class="layui-upload-img" id="demo1">
<p id="demoText"></p>
</div>
<button type="button" class="layui-btn layui-btn-normal" id="selectADocument">选择文件</button>
<button type="button" class="layui-btn" id="startUpload">开始上传</button>
</div>
</div>
1.2 uploadToLocal.js
layui.use('upload', function() {
var $ = layui.jquery
, upload = layui.upload;
//选完文件后不自动上传
upload.render({
elem: '#selectADocument'
,url: ctx+'/uploadApi/uploadToLocal'
,auto: false
,bindAction: '#startUpload'
// 选择完文件后,回调
,choose: function(obj){
//预读本地文件示例,不支持ie8
obj.preview(function(index, file, result){
$('#demo1').attr('src', result); //图片链接(base64)
});
}
,done: function(res){
if(res.code ==200 ){
return layer.msg(res.msg,{icon:1,time:1500});
}else{
return layer.msg(res.msg,{icon:5,time:1500});
}
}
});
})
1.3 config.properies
image=/Users/wangxianlin/Downloads/file/
1.4 ConfigUtil
public class ConfigUtil {
//初始化配置文件
private static Properties pro = null;
static {
Resource resource = new ClassPathResource("config.properties");
try {
pro = PropertiesLoaderUtils.loadProperties(resource);
} catch (IOException e) {
e.printStackTrace();
}
}
//获取配置文件的中配置的值
public static String getValue(String key){
return pro.getProperty(key);
}
//根据类名获取类对象
public static Object getInstance(String className){
Object obj = null;
try {
obj = Class.forName(getValue(className)).newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return obj;
}
}
1.5 CommonUtil
public class CommonUtil {
/**
* 格式化日日期
* @param date
* @param formatPattern
* @return
*/
public static final String format(Date date, String formatPattern) {
if (date == null) {
return "";
}
return new SimpleDateFormat(formatPattern).format(date);
}
}
1.6 UploadController
@Controller
@RequestMapping("uploadApi")
public class UploadController {
//跳转到图片上传界面
@GetMapping("/toUploadLocalView")
public String toUploadImage() {
return "upload/uploadToLocal";
}
//图片上传接口
@PostMapping("/uploadToLocal")
@ResponseBody
public Map<String,Object> uploadToLocal(@RequestParam("file") MultipartFile file,
HttpServletResponse response) {
Map<String,Object> result = new HashMap<>();
response.setContentType("text/html;charset=UTF-8");
if(file.isEmpty()) {
result.put("code", 500);
result.put("msg", "图片不能为空");
}else{
String fileName = file.getOriginalFilename();
try {
Date date = new Date();
String picDir = ConfigUtil.getValue("image");
String relativeDir = getRelativeDir(date);
File fileDir = new File(picDir + relativeDir);
if (!fileDir.exists()) {
fileDir.mkdirs();
}
//新的文件名
String newName = CommonUtil.format(date, "HHmmssSSS") +
Math.round(Math.random() * 8999 + 1000) +
fileName.substring(fileName.lastIndexOf("."));
//群头像地址
String imgPath = relativeDir + newName;
file.transferTo(new File(picDir + imgPath));
result.put("code", 200);
result.put("msg","上传成功");
result.put("data", imgPath);
} catch (Exception e) {
e.printStackTrace();
result.put("code", 500);
result.put("msg","图片上传发生未知异常,请联系管理员!");
}
}
return result;
}
/**
* 根据日期得到年/月/日/的相对路径
* @param date
* @return
*/
private String getRelativeDir(Date date) {
String year = CommonUtil.format(date, "yyyy");
String month = CommonUtil.format(date, "MM");
String day = CommonUtil.format(date, "dd");
String dir = year + "/" + month + "/" + day + "/";
return dir;
}
}
1.7 测试上传至本地
-
测试界面:
测试界面.png -
上传图片
image.png -
查看本地文件
image.png
2、将文件上传到服务器
- 上传至服务器会相对麻烦一些,有兴趣的话,请耐心的看下去就好了。
- uploadToServer.jsp、uploadToServer.js跟uploadToLocal.jsp、uploadToLocal.js是是一样的,唯一不同的地方就是:上传的接口是不一样的,测试的时候,更换一下就好了。
2.1 config.properies
#ftp上传配置
ftp.host=服务器IP
ftp.port=22
ftp.username=用户名
ftp.password=密码
server_file =/root/file/
2.2 SftpUtil
- 这个工具类里面我只写了上传至服务器的方法,代码太多了,我就没有全部放进去,望理解。如果需要完整的工具类,私聊或者留言。
public class SftpUtil {
private static final Logger LOGGER = LogManager.getLogger(SftpUtil.class);
private static final String FTP_HOST_IP = ConfigUtil.getValue("ftp.host");
private static final int FTP_PORT = Integer.parseInt(ConfigUtil.getValue("ftp.port"));
private static final String USER_NAME = ConfigUtil.getValue("ftp.username");
private static final String PASSWORD = ConfigUtil.getValue("ftp.password");
private static final int TIME_OUT = 5000;
public SftpUtil() {
}
public static ChannelSftp getSftpClient() {
ChannelSftp sftp = null;
try {
JSch jsch = new JSch();
Session sshSession = jsch.getSession(USER_NAME, FTP_HOST_IP, FTP_PORT);
sshSession.setPassword(PASSWORD);
Properties sshConfig = new Properties();
sshConfig.put("StrictHostKeyChecking", "no");
sshSession.setConfig(sshConfig);
sshSession.setTimeout(5000);
sshSession.connect();
Channel channel = sshSession.openChannel("sftp");
channel.connect();
sftp = (ChannelSftp)channel;
LOGGER.info("Connected to " + FTP_HOST_IP + ".");
} catch (Exception var5) {
LOGGER.catching(var5);
}
return sftp;
}
private static void cdDir(String dir, ChannelSftp sftp) {
try {
SftpATTRS sftpATTRS = sftp.lstat(dir);
boolean isDir = sftpATTRS.isDir();
if (isDir) {
LOGGER.info("目录已存在{}", isDir);
sftp.cd(dir);
} else {
LOGGER.error("不是目录", isDir);
}
} catch (SftpException var5) {
LOGGER.error("创建目录不存在,创建此目录..", var5);
try {
sftp.mkdir(dir);
sftp.cd(dir);
} catch (SftpException var4) {
LOGGER.error("创建目录失败", var4);
}
}
}
public static boolean upload(InputStream fis, String dir, String newFileName) {
ChannelSftp sftp = getSftpClient();
boolean flag = true;
boolean var13 = false;
Session sftpSession;
label112: {
try {
var13 = true;
cdDir(dir, sftp);
sftp.put(fis, newFileName);
var13 = false;
break label112;
} catch (Exception var17) {
LOGGER.info("sftp文件上传失败。。。");
flag = false;
LOGGER.catching(var17);
var13 = false;
} finally {
if (var13) {
try {
sftpSession = sftp.getSession();
if (sftp.isConnected()) {
sftp.disconnect();
}
if (sftpSession != null) {
sftpSession.disconnect();
}
} catch (JSchException var14) {
LOGGER.catching(var14);
}
}
}
try {
sftpSession = sftp.getSession();
if (sftp.isConnected()) {
sftp.disconnect();
}
if (sftpSession != null) {
sftpSession.disconnect();
return flag;
}
} catch (JSchException var15) {
LOGGER.catching(var15);
}
return flag;
}
try {
sftpSession = sftp.getSession();
if (sftp.isConnected()) {
sftp.disconnect();
}
if (sftpSession != null) {
sftpSession.disconnect();
}
} catch (JSchException var16) {
LOGGER.catching(var16);
}
return flag;
}
}
2.3 FileMeta
public class FileMeta {
private long fileId;
private String fileName;
private String fileSize;
private String fileType;
private String filePath;
private long downloadTimes;
//省略getter和setter方法
}
2.2 uploadController
//跳转到图片上传界面
@GetMapping("/uploadToServerView")
public String uploadToServerView() {
return "upload/uploadToServer";
}
public String getFilePath(Date date,String upload) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
int year = calendar.get(java.util.Calendar.YEAR);
int month = calendar.get(java.util.Calendar.MONTH) + 1;
int day = calendar.get(java.util.Calendar.DAY_OF_MONTH);
// 文件路径 upload/groupID/年月日
String monthStr = month < 10 ? "0" + month : "" + month;
String dayStr = day < 10 ? "0" + day : "" + day;
String filePath = upload + year + monthStr + dayStr;
return filePath;
}
@PostMapping("/uploadToServer")
@ResponseBody
public Map<String,Object> uploadToServer(@RequestParam("file") MultipartFile file) {
Map<String,Object> result = new HashMap<>();
//上传时间
Date createTime = new Date();
String upload = ConfigUtil.getValue("server_file");
//构造文件路径
//绝对路径
String fileAbsDir = getFilePath(createTime,upload);
//2.11附加非空判断 前台可能上传为空的情况
if(file.isEmpty()) {
//通过构造一个文件大小为-1的文件元数据对象返回
FileMeta fileMeta = new FileMeta();
fileMeta.setFileSize("-1");
result.put("code", 500);
result.put("msg", "图片不能为空");
}
//获取文件后缀名前面的点的位置
int i=file.getOriginalFilename().lastIndexOf(".");
//取文件后缀检验文件类型
String fileSuffix = file.getOriginalFilename().substring(i);
//上传文件大小限制为10M
if(file.getSize()<=10485760){
//2.3 创建文件元数据
FileMeta fileMeta = new FileMeta();
fileMeta.setFileSize(Math.floor(file.getSize()/(double)1024)+" Kb");
fileMeta.setFileType(file.getContentType());
String loadedFileName ="";
loadedFileName = new SimpleDateFormat("ddHHmmssSSS").format(createTime)+Math.round(Math.random()*8999+1000)+fileSuffix;
//将上传后的路径加文件名返回。用来刷新头像
fileMeta.setFileName(fileAbsDir+"/"+loadedFileName);
//因为防火墙问题,改用sftp
try {
SftpUtil.upload(file.getInputStream(), fileAbsDir, loadedFileName);
} catch (IOException e) {
e.printStackTrace();
}
result.put("code", 200);
result.put("msg", "上传成功");
result.put("data", fileMeta.getFileName());
}else{
//通过构造一个文件大小为-1的文件元数据对象返回
FileMeta fileMeta = new FileMeta();
fileMeta.setFileSize("-1");
result.put("code", 500);
result.put("msg", "图片不能超过10 MB");
}
return result;
}
2.3 测试上传只服务器
-
上传测试
image.png -
查看上传文件
服务器文件.png