一、引言
1. 课程概述

相信很多人都知道网站一般会有很多图片,对于小型网站来说,图片放在网站服务器上不算什么,但当图片数量很大时,会造成服务器很臃肿,相应地对带宽要求也会提高,这就造成了成本的增加。其实现在已经流行云存储,我们可以把图片、大文件等放到第三方提供的云存储服务上,这会减少一部分成本。这门课程就介绍了JavaWeb结合七牛云存储来搭建个人相册服务。


2. 预备知识

掌握Servlet+JSP,能了解Bootstrap更好。


二、Just Do It!

项目开始前,你需要有一个七牛云存储的标准用户账号,新建一个Bucket,知道你自己的Access Key和Secret Key。


1. 创建数据库

这里我们使用MySQL数据库,创建名称为photo的数据库:

create database photo DEFAULT CHARSET=utf8;

CREATE TABLE `image` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(16) DEFAULT NULL,
`url` varchar(255) DEFAULT NULL,
`date` datetime DEFAULT NULL,
`user_id` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8; CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(16) DEFAULT NULL,
`password` varchar(16) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

2. 创建JavaWeb项目

这里使用Eclipse创建一个名称为Photo的动态Web项目,加入Tomcat 7服务器,加入所需的jar包(源码中包含jar包),把Photo项目部署到Tomcat上。


3. 编写前端代码

前端使用Bootsrap,把css、fonts和js文件夹放到WebContent目录下。

创建index.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html lang="zh-cn">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>实验楼个人相册</title>
<link href="css/bootstrap.min.css" rel="stylesheet">
<!--[if lt IE 9]>
<script src="http://cdn.bootcss.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="http://cdn.bootcss.com/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<div class="row">
<div class="col-xs-12 text-center">
<h2>实验楼个人相册</h2>
</div>
</div>
<div class="row">
<div id="alert1" class="alert alert-success fade in text-center col-xs-2 col-xs-offset-5 hide">
<strong>注册成功</strong>
</div>
</div>
<form id="form" class="form-horizontal" role="form" style="margin-top: 73px;">
<div class="form-group" >
<label for="username" class="col-xs-2 control-label col-sm-offset-3" >用户名</label>
<div class="col-xs-2">
<input type="text" class="form-control" id="username" rel="tooltip"/>
</div>
</div>
<div class="form-group">
<label for="password" class="col-xs-2 control-label col-sm-offset-3">密码</label>
<div class="col-xs-2">
<input type="password" class="form-control" id="password"/>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-5 col-xs-1">
<button type="button" class="btn btn-success" id="login">登录</button>
</div>
<div class="col-sm-1">
<button type="button" class="btn btn-danger" data-toggle="modal" data-target="#myModal">注册</button>
</div>
</div>
</form>
</div> <!-- 注册对话框 begin -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<h4 class="modal-title" id="myModalLabel">用户注册</h4>
</div>
<div class="modal-body">
<form class="form-horizontal" role="form">
<div class="form-group" >
<label for="reg_username" class="col-xs-2 control-label" >用户名</label>
<div class="col-xs-4">
<input type="text" class="form-control" id="reg_username"/>
</div>
</div>
<div class="form-group">
<label for="reg_password" class="col-xs-2 control-label">密码</label>
<div class="col-xs-4">
<input type="password" class="form-control" id="reg_password"/>
</div>
</div>
<div class="form-group">
<label for="reg_repassword" class="col-xs-2 control-label">重复密码</label>
<div class="col-xs-4">
<input type="password" class="form-control" id="reg_repassword"/>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
<button type="button" class="btn btn-primary" id="register">注册</button>
</div>
</div>
</div>
</div>
<!-- 注册对话框 end --> <script src="http://cdn.bootcss.com/jquery/1.11.1/jquery.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
//点击登录
$('#login').click(function() {
//提交登录表单
$.post('${pageContext.request.contextPath}' + '/UserAction?type=1',
{
username: $('#username').val(),
password: $('#password').val()
},
function(data, status) {
if (data == '1') {
createPopOver('#username', 'right', '用户名不能为空', 'show');
} else if (data == '2') {
createPopOver('#password', 'right', '密码不能为空', 'show');
} else if (data == '3') {
createPopOver('#username', 'right', '用户名不存在', 'show');
} else if (data == '4') {
createPopOver('#password', 'right', '密码错误', 'show');
} else if (data == 5) {
location.href = '${pageContext.request.contextPath}' + '/home.jsp';
}
});
}); //点击注册按钮
$('#register').click(function() {
//提交注册表单
$.post('${pageContext.request.contextPath}' + '/UserAction?type=2',
{
username: $('#reg_username').val(),
password: $('#reg_password').val(),
repassword: $('#reg_repassword').val()
},
function(data, status) {
if (data == '1') {
createPopOver('#reg_username', 'right', '不能为空', 'show');
} else if (data == '2') {
createPopOver('#reg_password', 'right', '不能为空', 'show');
} else if (data == '3') {
createPopOver('#reg_repassword', 'right', '不能为空', 'show');
} else if (data == '4') {
createPopOver('#reg_repassword', 'right', '密码不一致', 'show');
} else if (data == '5') {
createPopOver('#reg_username', 'right', '用户名已存在', 'show');
} else if (data == '6') {
$('#reg_username').val('');
$('#reg_password').val('');
$('#reg_repassword').val('');
$('#myModal').modal('hide');
$('#alert1').removeClass('hide');
$('#form').css('margin-top', '0px');
}
});
}); //显示弹出框
function createPopOver(id, placement, content, action) {
$(id).popover({
placement: placement,
content: content
});
$(id).popover(action);
} //点击输入框时销毁弹出框
$('#username').click(function() {
$('#username').popover('destroy');
}); $('#password').click(function() {
$('#password').popover('destroy');
}); $('#reg_username').click(function() {
$('#reg_username').popover('destroy');
}); $('#reg_password').click(function() {
$('#reg_password').popover('destroy');
}); $('#reg_repassword').click(function() {
$('#reg_repassword').popover('destroy');
});
});
</script>
</body>
</html>

创建home.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<!DOCTYPE html>
<html lang="zh-cn">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>${user.username}的个人相册</title>
<link href="css/bootstrap.min.css" rel="stylesheet">
<!--[if lt IE 9]>
<script src="http://cdn.bootcss.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="http://cdn.bootcss.com/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<!-- 首部 start -->
<div class="row">
<div class="col-xs-8 col-xs-offset-2">
<h3 class="page-header">
${user.username} <small>共<span class="badge">${imageList.size()}</span>张</small>
<div class="btn-group pull-right">
<button type="button" class="btn btn-primary dropdown-toggle" data-toggle="dropdown">
操作<span class="caret"></span>
</button>
<ul class="dropdown-menu" role="menu">
<li><a href="#" data-toggle="modal" data-target="#myModa2">上传</a></li>
<li><a href="#" data-toggle="modal" data-target="#myModa3">删除</a></li>
<li><a href="#" data-toggle="modal" data-target="#myModa4">退出</a></li>
</ul>
</div>
</h3>
</div>
</div>
<!-- 首部 end --> <!-- 显示图片列表 -->
<c:forEach items="${imageList}" varStatus="status" var="image">
<c:choose>
<c:when test="${status.first or status.index % 4 eq 0}">
<div class="row">
<div class="col-xs-2 col-xs-offset-2">
<a href="#" class="thumbnail text-center">
<img name="${image.name}" date="<fmt:formatDate value='${image.date}' pattern='yyyy-MM-dd HH:mm'/>" style="width: 140px; height: 130px;" src="http://shiyanlouphoto.qiniudn.com/${image.url}">
<input class="pull-left" type="checkbox" value="${image.id}" url="${image.url}"/>${image.name }
</a>
</div>
</c:when>
<c:when test="${status.index % 4 eq 3 and not status.last }">
<div class="col-xs-2">
<a href="#" class="thumbnail text-center">
<img name="${image.name}" date="<fmt:formatDate value='${image.date}' pattern='yyyy-MM-dd HH:mm'/>" style="width: 140px; height: 130px;" src="http://shiyanlouphoto.qiniudn.com/${image.url}">
<input class="pull-left" type="checkbox" value="${image.id}" url="${image.url}" />${image.name }
</a>
</div>
</div>
</c:when>
<c:otherwise>
<div class="col-xs-2">
<a href="#" class="thumbnail text-center">
<img name="${image.name}" date="<fmt:formatDate value='${image.date}' pattern='yyyy-MM-dd HH:mm'/>" style="width: 140px; height: 130px;" src="http://shiyanlouphoto.qiniudn.com/${image.url}">
<input class="pull-left" type="checkbox" value="${image.id}" url="${image.url}"/>${image.name }
</a>
</div>
</c:otherwise>
</c:choose>
<c:if test="${status.last}">
</div>
</c:if>
</c:forEach>
<!-- 显示图片列表 end -->
</div> <!-- 显示图片对话框 start -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel"></h4>
</div>
<div class="modal-body" id="modal-content">
</div>
</div>
</div>
</div>
<!-- 显示图片对话框 end --> <!-- 上传图片对话框 start -->
<div class="modal fade" id="myModa2" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="myModalLabe2">图片上传</h4>
</div>
<div class="modal-body">
<form class="form-horizontal" role="form" id="form">
<div class="form-group" >
<label for="image_name" class="col-xs-2 control-label" >名称</label>
<div class="col-xs-4">
<input type="text" class="form-control" id="image_name" name="image_name"/>
</div>
</div>
<div class="form-group">
<label for="image" class="col-xs-2 control-label">图片</label>
<div class="col-xs-4">
<input type="file" id="image" name="image"/>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
<button type="button" class="btn btn-primary" id="upload">上传</button>
</div>
</div>
</div>
</div>
<!-- 上传图片对话框 end --> <!-- 删除图片对话框 start -->
<div class="modal fade" id="myModa3" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="myModalLabe3">确定删除吗?</h4>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
<button type="button" class="btn btn-danger" id="delete">确定</button>
</div>
</div>
</div>
</div>
<!-- 删除图片对话框 end --> <!-- 退出对话框 start -->
<div class="modal fade" id="myModa4" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="myModalLabe4">确定退出吗?</h4>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
<button type="button" class="btn btn-danger" id="exit">确定</button>
</div>
</div>
</div>
</div>
<!-- 退出对话框 end --> <script src="http://cdn.bootcss.com/jquery/1.11.1/jquery.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
//点击图片
$('img').click(function() {
$('#myModalLabel').html($(this).attr('name') + ' <small>' + $(this).attr('date') + '</small>');
$('#modal-content').html('<img class=\'img-responsive\' src=\'' + $(this).attr('src') + '\'/>');
$('#myModal').modal('show');
}); //点击上传
$('#upload').click(function() {
if ($('#image_name').val() == '' || $('#image').val() == '') {
} else {
$('#form').attr('action', '${pageContext.request.contextPath}' + '/ImageAction?type=1');
$('#form').attr('enctype', 'multipart/form-data');
$('#form').attr('method', 'post');
$('#form').submit();
}
}); //点击确定退出
$('#exit').click(function() {
$.get('${pageContext.request.contextPath}' + '/UserAction?type=3', function(data, status) {
location.href = '${pageContext.request.contextPath}' + '/index.jsp';
});
}); //点击确定删除图片
$('#delete').click(function() {
var ids = "";
var urls = "";
$('input[type=checkbox]:checked').each(function() {
ids += $(this).val() + ',';
urls += $(this).attr('url') + ',';
});
$.post('${pageContext.request.contextPath}' + '/ImageAction?type=2', {
ids: ids,
urls: urls
},function(data, status) {
$('#myModa3').modal('hide');
location.href = '${pageContext.request.contextPath}' + '/home.jsp';
});
});
});
</script>
</body>
</html>

4. 编写后台代码

创建User类:

/**
* 用户类
* [url=home.php?mod=space&uid=9083]@author[/url] www.shiyanlou.com
*
*/
@SuppressWarnings("serial")
public class User implements Serializable {
private int id; //用户ID
private String username; //用户名
private String password; //密码
private List<Image> images; //图片列表 public User() {
} public User(int id, String username, String password, List<Image> images) {
this.id = id;
this.username = username;
this.password = password;
this.images = images;
} public User(String username, String password) {
this.username = username;
this.password = password;
} public User(int id) {
this.id = id;
} public List<Image> getImages() {
return images;
} public void setImages(List<Image> images) {
this.images = images;
} public int getId() {
return id;
} public void setId(int id) {
this.id = id;
} public String getUsername() {
return username;
} public void setUsername(String username) {
this.username = username;
} public String getPassword() {
return password;
} public void setPassword(String password) {
this.password = password;
} }

创建Image类:

/**
* 图片类
* @author www.shiyanlou.com
*
*/
@SuppressWarnings("serial")
public class Image implements Serializable {
private int id; //图片ID
private String name; //图片名
private String url; //图片URL
private Date date; //上传时间
private User user; //所属用户 public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}

创建数据库工具类:

/**
* 数据库工具类
* @author www.shiyanlou.com
*
*/
public class DBUtils {
private static Connection connection = null;
private static PreparedStatement preparedStatement = null;
private static ResultSet resultSet = null; //初始化
static {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (Exception e) {
e.printStackTrace();
}
} /**
* 获取连接
* @return
*/
private static Connection getConnection() {
try {
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/photo?useUnicode=true&characterEncoding=UTF-8", "root", "root");
} catch (SQLException e) {
e.printStackTrace();
}
return connection;
} /**
* 关闭连接、预处理语句和结果集
* @param connection
* @param preparedStatement
* @param resultSet
*/
private static void close(Connection connection, PreparedStatement preparedStatement, ResultSet resultSet) {
try {
if (resultSet != null) {
resultSet.close();
resultSet = null;
} if (preparedStatement != null) {
preparedStatement.close();
preparedStatement = null;
} if (connection != null) {
connection.close();
connection = null;
}
} catch (Exception e) {
e.printStackTrace();
}
} /**
* 查询数据库
* @param sql SQL语句
* @param parameters 参数
* @return
*/
public static ArrayList<Object[]> query(String sql, String[] parameters) {
ArrayList<Object[]> list = new ArrayList<Object[]>();
try {
connection = getConnection();
preparedStatement = connection.prepareStatement(sql);
for (int i = 0; i < parameters.length; i++) {
preparedStatement.setString(i + 1, parameters[i]);
}
resultSet = preparedStatement.executeQuery();
int columnCount = resultSet.getMetaData().getColumnCount(); while (resultSet.next()) {
Object[] objects = new Object[columnCount];
for (int i = 0; i < columnCount; i++) {
objects[i] = resultSet.getObject(i + 1);
}
list.add(objects);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
close(connection, preparedStatement, resultSet);
}
return list;
} /**
* 更新数据库
* @param sqls SQL语句数组
* @param parameters 参数数组
*/
public static void updates(String[] sqls, String[][] parameters) {
try {
connection = getConnection();
connection.setAutoCommit(false);
for (int i = 0; i < sqls.length; i++) {
preparedStatement = connection.prepareStatement(sqls[i]);
for (int j = 0; j < parameters[i].length; j++) {
preparedStatement.setString(j + 1, parameters[i][j]);
}
preparedStatement.executeUpdate();
}
connection.commit();
} catch (Exception e) {
try {
connection.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
}
e.printStackTrace();
} finally {
close(connection, preparedStatement, resultSet);
}
}
}

创建文件工具类(使用了七牛云存储服务):

/**
* 图片工具类(使用七牛云存储服务)
* @author www.shiyanlou.com
*
*/
public class FileUtils {
private static final String ACCESS_KEY = "你自己的Access Key";
private static final String SECRET_KEY = "你自己的Secret Key";
private static final String BUCKET_NAME = "创建的Bucket的名称"; /**
* 上传图片到七牛云存储
* @param reader
* @param fileName
*/
public static void upload(InputStream reader, String fileName) {
String uptoken;
try {
Mac mac = new Mac(ACCESS_KEY, SECRET_KEY);
PutPolicy putPolicy = new PutPolicy(BUCKET_NAME);
uptoken = putPolicy.token(mac);
IoApi.Put(uptoken, fileName, reader, null);
} catch (AuthException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
} /**
* 删除七牛云存储上的图片
* @param key
*/
public static void delete( String key) {
Mac mac = new Mac(ACCESS_KEY, SECRET_KEY);
RSClient client = new RSClient(mac);
client.delete(BUCKET_NAME, key);
}
}

创建用户服务类:

/**
* 用户服务类
* @author www.shiyanlou.com
*
*/
public class UserService {
/**
* 通过用户名获取用户
* @param username 用户名
* [url=home.php?mod=space&uid=105031]@return[/url] 用户
*/
public User getUserByUsername(String username) {
String sql = "select id, username, password from user where username = ?";
String[] parameters = {username};
List<Object[]> users = DBUtils.query(sql, parameters);
if (users.size() == 0) {
return null;
} else {
Object[] objects = users.get(0);
return objects == null ? null : new User(Integer.parseInt(objects[0].toString()), objects[1].toString(), objects[2].toString(), null);
}
} /**
* 添加用户
* @param user 用户
*/
public void addUser(User user) {
String[] sqls = {"insert into user(username, password) values(?, ?)"};
String[][] parameters = {{user.getUsername(), user.getPassword()}};
DBUtils.updates(sqls, parameters);
}
}

创建图片服务类:

/**
* 图片服务类
* @author www.shiyanlou.com
*
*/
public class ImageService {
/**
* 通过用户ID获取图片列表
* @param userId 用户ID
* @return 图片列表
*/
public ArrayList<Image> getByUserId(int userId) {
ArrayList<Image> images = new ArrayList<Image>();
String sql = "select id, name, url, date, user_id from image where user_id = ? order by date desc";
String[] parameters = {userId + ""};
List<Object[]> imageList = DBUtils.query(sql, parameters);
for (Object[] objects : imageList) {
Image image = new Image();
image.setId(Integer.parseInt(objects[0].toString()));
image.setName(objects[1].toString());
image.setUrl(objects[2].toString());
image.setDate((Date) objects[3]);
image.setUser(new User(Integer.parseInt(objects[4].toString())));
images.add(image);
}
return images;
} /**
* 上传图片
* @param image 图片
* @param inputStream 输入流
*/
public void addImage(Image image, InputStream inputStream) {
FileUtils.upload(inputStream, image.getUrl());
String[] sqls = {"insert into image(name, url, date, user_id) values(?, ?, ?, ?)"};
String[][] parameters = {{image.getName(), image.getUrl(), new SimpleDateFormat("yyyy-MM-dd HH:mm").format(image.getDate()), image.getUser().getId() + ""}};
DBUtils.updates(sqls, parameters);
} /**
* 通过图片ID数组和图片URL数组删除图片
* @param ids 图片ID数组
* @param urls 图片URL数组
*/
public void delByIdsAndUrls(String ids, String urls) {
String[] idArray = ids.split(",");
String[] urlArray = urls.split(",");
if (!"".equals(idArray[0]) && !"".equals(urlArray[0])) {
String[] sqls = new String[idArray.length];
String[][] parameters = new String[idArray.length][1];
for (int i = 0; i < idArray.length; i++) {
FileUtils.delete(urlArray[i]);
sqls[i] = "delete from image where id = ?";
parameters[i][0] = idArray[i];
}
DBUtils.updates(sqls, parameters);
}
}
}

创建用户控制器类:

/**
* 用户控制器
* @author www.shiyanlou.com
*
*/
@WebServlet(value = "/UserAction")
public class UserAction extends HttpServlet {
private static final long serialVersionUID = 1L; /**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("Utf-8");
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
UserService userService = new UserService();
ImageService imageService = new ImageService(); Integer type = Integer.valueOf(request.getParameter("type"));
if (type == 1) { //用户登录
String username = request.getParameter("username");
String password = request.getParameter("password");
String result = null;
User user = null;
//验证用户是否有效
if (username.isEmpty()) {
result = "1";
} else if (password.isEmpty()) {
result = "2";
} else if ((user = userService.getUserByUsername(username)) == null) {
result = "3";
} else {
if (!user.getPassword().equals(password)) {
result = "4";
} else {
request.getSession().setAttribute("user", user);
request.getSession().setAttribute("imageList", imageService.getByUserId(user.getId()));
result = "5";
}
}
out.print(result);
} else if (type == 2) { //用户注册
String username = request.getParameter("username");
String password = request.getParameter("password");
String repassword = request.getParameter("repassword");
String result = null;
//验证有效性
if (username.isEmpty()) {
result = "1";
} else if (password.isEmpty()) {
result = "2";
} else if (repassword.isEmpty()) {
result = "3";
} else if (!repassword.equals(password)) {
result = "4";
} else if (userService.getUserByUsername(username) != null) {
result = "5";
} else {
User user = new User(username, password);
//添加用户
userService.addUser(user);
result = "6";
}
out.print(result);
} else if (type == 3) { //用户退出
request.getSession().invalidate();
}
} /**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
} }

创建图片控制器类:

/**
* 图片控制器
* @author www.shiyanlou.com
*
*/
@WebServlet(value = "/ImageAction")
@MultipartConfig
public class ImageAction extends HttpServlet {
private static final long serialVersionUID = 1L; /**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
Integer type = Integer.valueOf(request.getParameter("type"));
ImageService imageService = new ImageService(); if (type == 1) { //上传图片
String imageName = request.getParameter("image_name");
Part image = request.getPart("image");
Image img = new Image();
img.setDate(new Date());
img.setName(imageName);
img.setUser((User) request.getSession().getAttribute("user"));
img.setUrl(img.getUser().getUsername() + "/" + UUID.randomUUID());
imageService.addImage(img, image.getInputStream());
request.getSession().setAttribute("imageList", imageService.getByUserId(img.getUser().getId()));
response.sendRedirect(request.getContextPath() + "/home.jsp");
} else if (type == 2) { //删除图片
String ids = request.getParameter("ids");
String urls = request.getParameter("urls");
imageService.delByIdsAndUrls(ids, urls);
request.getSession().setAttribute("imageList", imageService.getByUserId(((User) request.getSession().getAttribute("user")).getId()));
}
} /**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
} }

5. 发布

把Photo部署到Tomcat上,启动服务器,访问http://127.0.0.1:8080/Photo



6.项目截图

图片1

 

图片2

 

 

图片3

 

 

图片4

 

 

图片5

 

 

图片6

 

 

图片7

 

 

图片8

 

 

图片9

 

如果有不懂和疑问欢迎登陆实验楼官方网站,http://www.shiyanlou.com/courses/

项目课大赛正在火热报名中,欢迎参加,一等奖三千元,入围就有百元红包!详情请戳http://www.shiyanlou.com/huodong/projects.html

JavaWeb结合七牛云存储搭建个人相册服务的更多相关文章

  1. 如何在WordPress中使用七牛云存储

    序:七牛云存储可以方便的将网站的图片等数据镜像到七牛云存储的空间,直接从云端将数据返回给用户.这样可以大大节省网站的空间,提升网站的访问速度. 真正显示一键实现WordPress博客静态文件CDN加速 ...

  2. 【UEditor】远程上传图片到【七牛云存储】

    杂谈:最近在玩一个第三方的微信开发平台,里面的图片都是上传到[七牛云存储]的,用了一下非常的好用,支持各种语言,SDK齐全.支持全分布式系统架构以及存储技术和数据加速,于是决定将网站的图片都存储到七牛 ...

  3. 七牛云存储官方接口PHP版本

    PHP SDKv6 此 SDK 适用于 PHP 5.1.0 及其以上版本.基于 七牛云存储官方API 构建.使用此 SDK 构建您的网络应用程序,能让您以非常便捷地方式将数据安全地存储到七牛云存储上. ...

  4. Node开发文件上传系统及向七牛云存储和亚马逊AWS S3的文件上传

    背景起,有奏乐: 有伟人曰:学习技能的最好途径莫过于理论与实践相结合. 初学Node这货时,每每读教程必会Fall asleep. 当真要开发系统时,顿觉精神百倍,即便踩坑无数也不失斗志. 因为同团队 ...

  5. 七牛云存储的 Javascript Web 前端文件上传

    因为我的个人网站 restran.net 已经启用,博客园的内容已经不再更新.请访问我的个人网站获取这篇文章的最新内容,七牛云存储的 Web 前端文件上传 七牛是不错的云存储产品,特别是有免费的配额可 ...

  6. WP集成七牛云存储(原创)

    借助:七牛镜像存储 WordPress 插件 https://wordpress.org/plugins/wpjam-qiniu/ 安装本插件1.4.5及以上版本,请先安装并激活WPJAM BASIC ...

  7. 使用Qiniu-JavaScript-SDK上传文件至七牛云存储

    一.Qiniu-JavaScript-SDK介绍 基于 JS-SDK 可以方便的从浏览器端上传文件至七牛云存储,并对上传成功后的图片进行丰富的数据处理操作. JS-SDK 兼容支持 H5 File A ...

  8. xadmin引入django-qiniu-storage七牛云存储图片

    一.注册七牛云账号: 1.注册并完成实名认证 2.创建公有存储空间 二.安装django-qiniu-storage: pip install django-qiniu-storage 安装djang ...

  9. OneinStack定时同步备份数据库/网站至七牛云存储方法

    无论我们用WEB面板,还是用一键脚本安装环境建站,只要一旦我们开始用VPS.服务器,最为关键的就是服务器中的数据.因为大部分VPS.服务器商家都是无管理型主机,任何的安装和维护都需要我们自行管理.即便 ...

随机推荐

  1. 关于SubSonic3.0插件使用SqlQuery或Select查询时产生的System.NullReferenceException异常修复

    早上在编写执行用例时,突然爆异常System.NullReferenceException: 未将对象引用设置到对象的实例 执行代码:

  2. 附录E 安装Kafka

    E.1   安装Kafka E.1.1    下载Kafka Kafka是由LinkedIn设计的一个高吞吐量.分布式.基于发布订阅模式的消息系统,使用Scala编写,它以可水平扩展.可靠性.异步通信 ...

  3. 使用Oracle调度程序自动完成任务

    1. 创建作业.计划和时间表 2. 创建轻量级作业 3. 使用作业链执行一系列相关任务 4. 创建窗口和作业类 5. 使用高级调度程序概念确定作业优先顺序 Reference 实验演示准备: --业务 ...

  4. Windows Server 2008 下解析二级域名的方法

    昨天去了客户那里部署网站,用的是客户那边的windows server 2008. 本文主要以总结问题点的形式来说. 问题1:本机的数据库是SQL SERVER 2008R2,客户那边的数据库是SQL ...

  5. 代码的坏味道(4)——过长参数列(Long Parameter List)

    坏味道--过长参数列(Long Parameter List) 特征 一个函数有超过3.4个入参. 问题原因 过长参数列可能是将多个算法并到一个函数中时发生的.函数中的入参可以用来控制最终选用哪个算法 ...

  6. 我有几个NUMA节点

    在SQL Server交流会,经常被问到的一个问题,SQL Server在几个NUMA节点上运行.因此,在今天的文章里,我想向你展示下几个方法和技术,找出你的SQL Server有几个NUMA节点. ...

  7. MySQL数据迁移到SQL Server

    数据迁移的工具有很多,基本SSMA团队已经考虑到其他数据库到SQL Server迁移的需求了,所以已经开发了相关的迁移工具来支持. 此博客主要介绍MySQL到SQL Server数据迁移的工具:SQL ...

  8. 我的runtime学习笔记

    0.简介: OC方法不同于C语言函数,属于动态调用过程,在编译的时候并不能决定真正调用哪个函数,只有在真正运行的时候才会根据函数的名称找到对应的函数来调用. 至于其他理论上的东西不必讲太多,编程讲的就 ...

  9. VS2013设置护眼背景颜色

    打开VS2013 —> 工具 —> 选项 —> 环境 —> 字体和颜色 —> 选择显示项中的纯文本 —> 项目背景 —> 自定义—> 色调位85.饱和度 ...

  10. [Asp.net 5] Logging-日志系统的基本架构(下)

    接上节内容,我们继续讲解日志的其他部分. ILoggerProvider以及扩展类 我们在上节的架构图上并没有看到有直接实现该接口的实现类.那么如果将Logger类直接使用会有什么结果呢? var f ...