首页 > 代码库 > 图片上传
图片上传
图片的保存路径是在运行项目中.即WebContent/attachment
update.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://"
+ request.getServerName() + ":" + request.getServerPort()
+ path + "/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="http://www.mamicode.com/">
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<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="http://www.mamicode.com/styles.css">
-->
<link href="http://www.mamicode.com/assets/css/bootstrap.min.css" rel="stylesheet">
<style type="text/css">
html,body,#wrapper {
width: 100%;
height: 100%;
}
.navbar-inverse {
border-radius: 0;
margin-bottom: 0;
}
.navbar-inverse .navbar-header {
width: 180px;
text-align: center;
border-right: 1px solid rgba(255, 255, 255, 0.4);
}
.navbar-inverse .navbar-header .navbar-brand {
float: none;
display: inline-block;
}
.slider {
width: 180px;
min-width: 180px;
top: 52px;
bottom: 0;
position: absolute;
background-color: rgba(0, 0, 0, 0.00);
box-shadow: 3px 0 6px rgba(0, 0, 0, 0.3)
}
.slider .nav li a:hover,.slider .nav li.active>a {
background-color: rgba(0, 0, 0, 0.2) !important;
}
.slider .sub-menu li a {
padding-left: 40px;
}
.slider .sub-menu { /* border-bottom:1px solid #e5e5e5; */
border-top: 1px solid #e5e5e5;
}
#wrap {
margin: 0 0 0 180px;
}
#wrap .wrap {
padding: 5px 10px;
}
.panel .panel-footer {
background-color: #ffffff;
padding: 0 15px;
}
.panel-footer .pagination {
margin: 5px;
}
</style>
</head>
<body>
<div id="wrapper">
<nav class="navbar navbar-inverse"> <!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<a class="navbar-brand" href="http://www.mamicode.com/#">后台系统</a>
</div>
<ul class="nav navbar-nav">
<li class="active"><a href="http://www.mamicode.com/#">首 页 <span class="sr-only">(current)</span></a></li>
<li><a href="http://www.mamicode.com/views/login.jsp">登 录</a></li>
<li class="dropdown"><a href="http://www.mamicode.com/#" class="dropdown-toggle"
data-toggle="dropdown" role="button" aria-haspopup="true"
aria-expanded="false">更 多 <span class="caret"></span></a>
<ul class="dropdown-menu">
<li><a href="http://www.mamicode.com/#">注 册</a></li>
<li><a href="http://www.mamicode.com/#">Another action</a></li>
<li><a href="http://www.mamicode.com/#">Something else here</a></li>
<li role="separator" class="divider"></li>
<li><a href="http://www.mamicode.com/#">Separated link</a></li>
<li role="separator" class="divider"></li>
<li><a href="http://www.mamicode.com/#">One more separated link</a></li>
</ul></li>
</ul>
<ul class="nav navbar-nav pull-right">
<li><a href="http://www.mamicode.com/logout" title="安全退出">安全退出</a></li>
</ul>
</nav>
<div class="slider">
<ul class="nav">
<li class="active"><a href="javascript:void(0);"
onclick="openOrClose(this)"><i class="glyphicon glyphicon-user"></i>
用户管理 <i class="glyphicon glyphicon-chevron-down pull-right"></i></a>
<ul class="nav sub-menu">
<li><a href="http://www.mamicode.com/users/usersController?_method=findAll"><i
class="glyphicon glyphicon-list"></i> 用户列表</a></li>
<li class="active"><a href="http://www.mamicode.com/#"><i
class="glyphicon glyphicon-plus"></i> 用户添加</a></li>
</ul></li>
<li><a href="javascript:void(0);" onclick="openOrClose(this)"><i
class="glyphicon glyphicon-th-list"></i> 地址管理 <i
class="glyphicon glyphicon-chevron-left pull-right"></i></a>
<ul class="nav sub-menu hidden">
<li><a href="http://www.mamicode.com/#"><i class="glyphicon glyphicon-list"></i>
地址列表</a></li>
<li><a href="http://www.mamicode.com/#"><i class="glyphicon glyphicon-plus"></i>
地址添加</a></li>
</ul></li>
</ul>
</div>
<div id="wrap">
<div class="wrap">
<div class="panel panel-info">
<div class="panel-heading">修改用户</div>
<div class="panel-body">
<form class="form-horizontal" method="post" action="users/usersController?_method=update"
enctype="multipart/form-data">
<div class="row">
<div class="col-lg-8">
<div class="row">
<div class="col-lg-6">
<div class="form-group">
<label class="col-sm-3 control-label text-right">用户名</label>
<div class="col-sm-9">
<input type="text" class="form-control" name="username" placeholder="用户名" value="http://www.mamicode.com/${users.username }">
</div>
</div>
</div>
<div class="col-lg-6">
<div class="form-group">
<label class="col-sm-3 control-label text-right">密 码</label>
<div class="col-sm-9">
<input type="password" class="form-control" name="password" placeholder="密码" value="http://www.mamicode.com/${users.password }">
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-lg-6">
<div class="form-group">
<label class="col-sm-3 control-label text-right">邮 箱</label>
<div class="col-sm-9">
<input type="text" class="form-control" name="email" placeholder="邮箱" value="http://www.mamicode.com/${users.email }">
</div>
</div>
</div>
<div class="col-lg-6">
<div class="form-group">
<label class="col-sm-3 control-label text-right">年 龄</label>
<div class="col-sm-9">
<input type="text" class="form-control" name="age" placeholder="年龄" value="http://www.mamicode.com/${users.age }">
<input type="hidden" name="id" value="http://www.mamicode.com/${users.id }">
</div>
</div>
</div>
</div>
<div class="row">
<div class="form-group">
<div class="col-sm-offset-2">
<button type="reset" class="btn btn-default">重 置</button>
<button type="submit" class="btn btn-default">更 新</button>
</div>
</div>
</div>
</div>
<div class="col-lg-4">
<img src="http://www.mamicode.com/${users.image }" class="img-thumbnail text-center" height="200px">
<div class="form-group">
<label class="col-sm-3 control-label text-right">头 像</label>
<div class="col-sm-9">
<input type="file" name="image" class="form-control">
</div>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</body>
<script type="text/javascript" src="http://www.mamicode.com/assets/js/jquery-1.11.3.min.js"></script>
<script type="text/javascript" src="http://www.mamicode.com/assets/js/bootstrap.min.js"></script>
<script type="text/javascript">
//打开或是关闭菜单
function openOrClose(_dom) {
var sub_menu = getNextSilbing(_dom);
var flag = _dom.querySelector(".pull-right");
//如果包含某些样式 则做一些事情
if (hasClass(sub_menu, "hidden")) {
//去掉 关于隐藏的class
removeClass(sub_menu, "hidden");
//去掉菜单上的向左的箭头
removeClass(flag, "glyphicon-chevron-left");
//添加上向下的箭头
addClass(flag, "glyphicon-chevron-down");
} else {
//添加是 隐藏的class
addClass(sub_menu, "hidden");
//移除向下的箭头
removeClass(flag, "glyphicon-chevron-down");
//添加上向左的箭头
addClass(flag, "glyphicon-chevron-left");
}
//console.log();
}
//得到下一个兄弟节点
function getNextSilbing(_dom) {
_dom = _dom.nextSibling;
while (_dom.nodeType != 1) {
_dom = _dom.nextSibling;
}
return _dom;
}
//判断是否包含没有个class样式
function hasClass(_dom, _className) {
if (_dom.className.indexOf(_className) != -1) {
return true;
}
return false;
}
//给指定的元素添加指定的样式
function addClass(_dom, _className) {
_dom.className = _dom.className + " " + _className;
}
//给指定的元素移除指定的样式
function removeClass(_dom, _className) {
_dom.className = _dom.className.replace(_className, "");
//将每次添加上的多余的空格去掉
_dom.className = _dom.className.replace(/\s+/ig, " ");
}
</script>
</html>
UsersController.java
package com.huawei.controller;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import com.cdsxt.common.Page;
import com.cdsxt.po.Users;
import com.cdsxt.service.UsersService;
/**
* Servlet implementation class UsersController
*/
public class UsersController extends HttpServlet {
private static final long serialVersionUID = 1L;
private UsersService usersService = new UsersService();
/**
* @see HttpServlet#HttpServlet()
*/
public UsersController() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
this.doPost(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
/**
* 将 当前的doPost方法 当作中专站
*/
String _method = request.getParameter("_method");
if("findAll".equalsIgnoreCase(_method)){
this.findAll(request, response);
}else if("deleteById".equalsIgnoreCase(_method)){
this.deleteById(request, response);
}else if("register".equalsIgnoreCase(_method)){
this.register(request, response);
}else if("findById".equalsIgnoreCase(_method)){
this.findById(request, response);
}else if("update".equalsIgnoreCase(_method)){
this.update(request, response);
}
}
private void update(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
Users curr = (Users) request.getSession().getAttribute("admin");
if(ServletFileUpload.isMultipartContent(request)){
Map<String, FileItem> map = new HashMap<String, FileItem>();
//创建工厂
DiskFileItemFactory factory = new DiskFileItemFactory();
//得到JVM提供的缓存目录
ServletContext context = this.getServletContext();
File repository = (File)context.getAttribute("javax.servlet.context.tempdir");
factory.setRepository(repository);
//创建ServletFileUpload
ServletFileUpload upload = new ServletFileUpload(factory);
//解析请求
try {
List<FileItem> items = upload.parseRequest(request);
//users = new Users();
for(FileItem item:items){
//form表单里面的每一个字段
map.put(item.getFieldName(), item);
}
Users u = new Users();
u.setId(Integer.parseInt(map.get("id").getString()));
u.setUsername(map.get("username").getString());
u.setPassword(map.get("password").getString());
u.setEmail(map.get("email").getString());
//u.setImage(Integer.parseInt(map.get("id").getString()));
u.setAge(Integer.parseInt(map.get("age").getString()));
//处理 前一步的数据没有顺序的问题
//for(String key:map.keySet()){
//FileItem item = map.get(key);
//if(item.isFormField()){
//没有顺序
//}else{
//得到跟路径
String path = context.getRealPath("/");
//得到附件目录
File attachment = new File(path,"attachment/"+map.get("username").getString());
//如果没有 就创建目录
System.out.println(attachment.getAbsolutePath());
System.out.println(attachment.exists());
if(!attachment.exists()){
attachment.mkdirs();
}
FileItem image = map.get("image");
File output = new File(attachment,System.currentTimeMillis()+"."+getSuffix(image.getName()));
image.write(output);
u.setImage("attachment/"+map.get("username").getString()+"/"+output.getName());
//System.currentTimeMillis()
this.usersService.update(u);
this.findAll(request, response);
//}
//}
//map.get("id");
} catch (Exception e) {
e.printStackTrace();
}
}
}
private String getSuffix(String name){
if(name!=null){
String[] suffixs = name.split("\\.");
if(suffixs.length>1){
return suffixs[suffixs.length-1];
}
}
return "";
}
private void findById(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
String id = request.getParameter("id");
if(id!=null && id.trim()!=""){
Users users = this.usersService.findById(Integer.parseInt(id));
request.setAttribute("users", users);
request.getRequestDispatcher("/views/update.jsp").forward(request, response);
return ;
}
}
private void register(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
Users users = null;
//判断是否有文件上传
if(ServletFileUpload.isMultipartContent(request)){
//创建工厂
DiskFileItemFactory factory = new DiskFileItemFactory();
//得到JVM提供的缓存目录
ServletContext context = this.getServletContext();
File repository = (File)context.getAttribute("javax.servlet.context.tempdir");
factory.setRepository(repository);
//创建ServletFileUpload
ServletFileUpload upload = new ServletFileUpload(factory);
//解析请求
try {
List<FileItem> items = upload.parseRequest(request);
users = new Users();
for(FileItem item:items){
//form表单里面的每一个字段
}
//得到跟路径
String path = context.getRealPath("/");
//得到附件目录
File attachment = new File(path,"attachment");
//如果没有 就创建目录
if(!attachment.exists()){
attachment.mkdirs();
}
} catch (FileUploadException e) {
e.printStackTrace();
}
}
}
protected void deleteById(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String id = request.getParameter("id");
this.usersService.deleteById(Integer.parseInt(id));
response.sendRedirect("usersController?_method=findAll");
}
protected void findAll(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//List<Users> users = this.usersService.findAll();
//request.setAttribute("users", users);
String keyword = request.getParameter("keyword");
if(keyword==null){
keyword = "";
}
Page page = new Page();
String curr = request.getParameter("curr");
if(curr ==null || curr.trim().equals("")){
curr ="1";
}
page.getKeywords().put("username", keyword);
page.setCurr(Integer.parseInt(curr));
page = this.usersService.find4Page(page);
request.setAttribute("page", page);
request.getRequestDispatcher("/views/index.jsp").forward(request, response);
return;
}
}
图片上传