这是Nginx+Ftp+Fileinput做图片上传显示服务器的最后一篇,结合之前的SSM框架开始做上传显示。之前的SSM搭建的简易登录系统http://blog.csdn.net/a1369508468/article/details/63253599
之前忘了贴出数据库字段,就在这里一并贴出:
一、JSP页面编写
fileinput上传组件下载:http://download.csdn.net/download/shunyadu/8539737
上传页面编写代码:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"/>
<title>上传图片</title>
<link href="/SSM/resource/css/bootstrap.min.css" rel="stylesheet">
<link href="/SSM/resource/css/fileinput.css" media="all" rel="stylesheet" type="text/css" />
<script src="/SSM/resource/js/jquery-2.0.3.min.js"></script>
<script src="/SSM/resource/js/fileinput.js" type="text/javascript"></script>
<script type="text/javascript" src="/SSM/resource/js/fileinput_locale_zh.js"></script>
<script src="/SSM/resource/js/bootstrap.min.js" type="text/javascript"></script>
</head>
<body>
<div class="container kv-main">
<br>
<form enctype="multipart/form-data">
<div class="form-group">
<input id="file-1" type="file" name="file" multiple class="file" data-overwrite-initial="false" data-min-file-count="2">
</div>
</form>
</div>
<div align="center">
<input type="button" name="clickBtn" class="btn btn-primary" id="clickBtn" value="点击查看上传的图片" />
</div>
</body>
<script>
$("#file-1").fileinput({
uploadUrl: '/SSM/user/ftpUpload', //上传地址
allowedFileExtensions : ['jpg', 'png','gif'],
overwriteInitial: false,
maxFileSize: 1000,
maxFilesNum: 10,
minFilesNum:1,
}).on("fileuploaded",function(event,data){
if(data.response.status == 200){
alert(data.response.message);
return;
}else{
alert(data.response.message);
}
});
$(function(){
$("#clickBtn").click(function(){
window.location.href="/SSM/user/showImages";
});
});
</script>
</html>
显示页面编写:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html lang="en">
<head>
<title>用户上传的图片</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
<link rel="stylesheet" href="/SSM/resource/css/bootstrap.min.css" type="text/css"></link>
<script type="text/javascript" src="/SSM/resource/js/bootstrap.min.js"></script>
</head>
<body>
<c:choose>
<c:when test="${empty imageList }">
<span style="text-align:center;color:#666;font-size:25px;">未检测到图片</span>
</c:when>
<c:otherwise>
<c:forEach items="${imageList }" var="item">
<img src="http://192.168.127.128/${item.imageUrl }" class="img-rounded" width="400px" height="300px" style="float:left;padding-left:10px;padding-top:10px;">
</c:forEach>
</c:otherwise>
</c:choose>
</body>
</html>
二、JAVA代码编写(代码的增加和修改都是基于之前写的搭建SSM环境上)
新增jar包:
commons-net-1.4.1.jar
commons-fileupload-1.2.1.jar
SpringMVC增加文件上传解析
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 设置默认编码 -->
<property name="defaultEncoding" value="utf-8" />
<!-- 设置文件大小的最大值 -->
<property name="maxUploadSize" value="10485760000" />
</bean>
Domain层代码:
新增UserImage实体
package com.xw.demo.domain;
import java.io.Serializable;
public class UserImage implements Serializable {
private static final long serialVersionUID = -8583470494455131191L;
//ID
private Integer id;
//图片链接
private String imageUrl;
//用户id
private Integer userId;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
}
Mapper层代码:
新增UserImageMapper
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!-- 映射对应的接口路径 -->
<mapper namespace="com.xw.demo.dao.UserImageDao">
<resultMap type="com.xw.demo.domain.UserImage" id="UserImageMap">
<id column="id" property="id" />
<result column="imageUrl" property="imageUrl" />
<result column="userId" property="userId" />
</resultMap>
<!-- 根据用户ID查询的方法 -->
<select id="selectById" resultMap="UserImageMap" >
SELECT * FROM TB_USER_IMAGE WHERE USERID = #{id};
</select>
<!-- 新增方法 -->
<insert id="insertUserImage">
INSERT INTO TB_USER_IMAGE (IMAGEURL,USERID) values (#{imageUrl},#{userId});
</insert>
</mapper>
Dao层代码:
新增UserImageDao
package com.xw.demo.dao;
import java.util.List;
import com.xw.demo.domain.UserImage;
public interface UserImageDao {
/**
* 插入数据
* @param userImage
* @return 受影响的行数
*/
public int insertUserImage(UserImage userImage);
/**
* 根据ID查询数据
* @param id
* @return List<UserImage> 查询的集合
*/
public List<UserImage> selectById(int id);
}
Service层代码:
新增UserImageService和UserImageServiceImpl
UserImageService:
package com.xw.demo.service;
import java.util.List;
import com.xw.demo.domain.UserImage;
public interface UserImageService {
/**
* 插入数据
* @param userImage
* @return 受影响的行数
*/
public int insertUserImage(UserImage userImage);
/**
* 根据ID查询数据
* @param id
* @return List<UserImage> 查询的集合
*/
public List<UserImage> selectById(int id);
}
UserImageServiceImpl
package com.xw.demo.service.impl;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import com.xw.demo.dao.UserImageDao;
import com.xw.demo.domain.UserImage;
import com.xw.demo.service.UserImageService;
@Service("userImageService")
public class UserImageServiceImpl implements UserImageService {
@Resource
private UserImageDao userImageDao;
/**
* 插入数据
* @param userImage
* @return row 受影响的行数
*/
public int insertUserImage(UserImage userImage) {
int row = userImageDao.insertUserImage(userImage);
return row;
}
public List<UserImage> selectById(int id) {
List<UserImage> list = userImageDao.selectById(id);
return list!=null && list.size()>0?list:null;
}
}
UserController层代码:
package com.xw.demo.controller;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import com.xw.demo.domain.User;
import com.xw.demo.domain.UserImage;
import com.xw.demo.service.UserImageService;
import com.xw.demo.service.UserService;
@Controller
@RequestMapping("/user")
public class UserController {
@Resource
private UserService userService;
@Resource
private UserImageService userImageService;
private final static String LOGIN_PAGE = "/login";
private final static String USER_UPLOAD = "/upload";
private final static String SHOW_IMAGES = "/showImages";
//跳转到登录页面
@RequestMapping(value = "/login",method = RequestMethod.GET)
public String tologin(){
return LOGIN_PAGE;
}
//跳转到上传页面
@RequestMapping(value = "/upload",method = RequestMethod.GET)
public String toUpload(HttpSession session){
//取出Session验证
User user = (User) session.getAttribute("loginUser");
if(user == null || "".equals(user)){
return LOGIN_PAGE;
}
return USER_UPLOAD;
}
//登录验证
@RequestMapping(value = "/loginCheck", method = RequestMethod.POST)
@ResponseBody
public Map<Object,String> login(String username,String password,HttpSession session){
Map<Object,String> map = new HashMap<Object, String>();
User user = userService.selectByUsername(username);
if(user != null && user.getPassword().equals(password)){
//登录成功后存储Session
session.setAttribute("loginUser", user);
map.put("status", "200");
map.put("message", "登陆成功!");
}else{
map.put("status", "300");
map.put("message", "用户名或者密码错误!");
}
return map;
}
//上传
@RequestMapping(value = "/ftpUpload",method = RequestMethod.POST)
@ResponseBody
public Map<Object,String> upload(String userid,MultipartFile file,HttpSession session) throws Exception{
final Map<Object,String> map = new HashMap<Object, String>();
//取出Session验证
User user = (User) session.getAttribute("loginUser");
if(user == null && "".equals(user)){
map.put("status", "300");
map.put("message", "为检测到登录信息!");
return map;
}else{
FTPClient ftp = new FTPClient();
int reply;//用来接收响应码
String hostname = "192.168.127.128";//ftp的IP地址
String username = "test"; //ftp用户名
String password = "test";//ftp密码
int port = 21;//端口
ftp.connect(hostname, port);
ftp.login(username, password);
reply = ftp.getReplyCode();
//System.out.println("响应码:"+reply);
if(!(FTPReply.isPositiveCompletion(reply))){
map.put("message", "FTP连接错误");
return map;
}
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
//取当前日期作为文件夹
String dateFile = sdf.format(new Date());
//System.out.println("格式化后的date:"+dateFile);
//生成随机文件名
String fileName = UUID.randomUUID()+".jpg";
//System.out.println("文件名:"+fileName);
//拼接上传的路径
String uploadPath = "uploadImage/"+dateFile+"/"+fileName;
//System.out.println("上传的路径:"+uploadPath);
//创建文件夹 必须一层一层创建
ftp.makeDirectory("uploadImage");
ftp.makeDirectory("uploadImage"+"/"+dateFile);
if(!(ftp.changeWorkingDirectory(uploadPath))){
ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
if(ftp.storeFile(uploadPath, file.getInputStream())){
//上传成功将数据存到数据库
UserImage userImage = new UserImage();
userImage.setImageUrl(uploadPath);
userImage.setUserId(user.getId());
int row = userImageService.insertUserImage(userImage);
if(row > 0){
map.put("status", "200");
map.put("message", "上传成功!");
//System.out.println("上传成功!");
}else{
map.put("status", "300");
map.put("message", "上传失败!");
//System.out.println("上传失败");
}
}else{
map.put("status", "300");
map.put("message", "上传失败!");
//System.out.println("上传失败");
}
file.getInputStream().close();
ftp.logout();
}
}
return map;
}
//跳转到图片显示页
@RequestMapping(method = RequestMethod.GET,value = "/showImages")
public String showImages(HttpSession session,ModelMap map) throws Exception{
User user = (User) session.getAttribute("loginUser");
if(user == null || "".equals(user)){
return LOGIN_PAGE;
}
List<UserImage> imageList = userImageService.selectById(user.getId());
if(imageList != null && imageList.size() >0){
System.out.println(imageList.size());
map.put("imageList", imageList);
}
return SHOW_IMAGES;
}
}
三、测试上传:
上传页面:
上传成功:
数据库存储路径:
四、显示页面
Nginx的设置:
修改nginx.conf文件:
没有上传图片时显示:
上传后有图显示:
图片地址:
图片上传和显示的到这里就写完了,由于比较忙所以拖了很久才写完。虽然是第二次写,但在配置nginx,ftp和ssm时还是遇到一些之前没有遇到的问题,好在有万能的百度和谷歌可以看到许多大牛是怎么解决的。每一个错误都算是一次经验的积累。由于刚刚接触博客,所以写的也不怎么详细,代码优化可能也不够好,若有错误以及哪些地方做的不好需要优化还请各位大牛及时指出。