您的位置:首页 > 编程语言 > Java开发

关于springmvc上传图片

2015-07-31 14:56 483 查看
最近在项目中需要实现图片的上传,并且成功后返回图片上传保存路径,通过查找资料探索研究,实现了项目功能需求,记在这方便自己以后查阅,也为有同样需求的码友分享,功能实现比较简单,如果有好的建议和实现方法,还望多多指教。

主要将实现一下两个功能:
1、使用commons-fileupload实现文件的上传(包括图片);

2、使用jquery-form.js实现表单提交成功的回调函数。

3,spring的管理还需要:commons-io-2.2.jar

代码:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>H5后台管理系统</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="JS/jquery-1.8.3.js"></script>
<link rel="stylesheet" href="CSS/addGame.css" />
<script type="text/javascript">
function login(){
var gid=$("#gid").val();
var gimg=$("#gimg").val();
/*var lujing=$("#gimg").attr("src"); */
var gname=$("#gname").val();
var giIntroduction=$("#giIntroduction").val();
var gtype=$("#gtype").val();
var gtime=$("#gtime").val();
var gurl=$("#gurl").val();
var gjishu=$("#gjishu").val();
var gopen=$("#gopen").val();
var goptime=$("#goptime").val();
var gtypeurl=$("#gtypeurl").val();
if(gid==""||gimg==""||gname==""||giIntroduction==""||gtype==""||gtime==""||gurl==""||gopen==""||goptime==""||gtypeurl==""){
alert("请认真填写每一项。");
return ;
}else{
$("#formtj").submit();
}
}
function reset001(){
$("#formtj input").val("");
}
</script>
</head>
<body>
<form action="/BigMillionaire/MyBox/addGameSys.do" enctype="multipart/form-data" method="post" id="formtj" name="formtj">
<div class="all">
<div class="top">欢迎来到H5后台管理系统</div>
<!--中部样式-->
<div class="center">
<div class="center001">
<label class="usernamebutton">游戏ID</label>
<input class="username_inpu lable01" id="gid" type="text" name="game_id" value="" />
</div>

<div class="center001 mtop ">
<label>游戏icon</label>
<input class="incon" id="game" name="gameimg" type="file"  />
</div>

<div class="center001 mtop ">
<label class="usernamebutton">游戏名</label>
<input class="username_inpu lable02" id="gname" type="text" name="game_name"value="" />
</div>

<div class="center001 mtop ">
<label class="usernamebutton">游戏介绍</label>
<input class="username_inpu lable03" id="giIntroduction" type="text" name="game_shuoMing" value="" />
</div>

<div class="center001 mtop ">
<label  class="usernamebutton">游戏类型</label>
<select name="game_type" class="Dropbox lable05" id="gtype" value="">
<option value="1">飞行射击</option>
<option value="2">挂机放置</option>
<option value="3">角色扮演</option>
<option value="4">益智休闲</option>
</select>
</div>

<div class="center001 mtop ">
<label class="usernamebutton">上线时间</label>
<input class="username_inpu lable04" id="gtime" type="text" name="game_time" value=""  pattern="[0-9]{4}-[0-9]{2}-[0-9]{2}"
required="required" autofocus />(格式:xxxx-xx-xx,最新栏,时间越大越靠前)
</div>

<div class="center001 mtop ">
<label class="usernamebutton">路径</label>
<input class="username_inpu lable06" id="gurl" type="text" name="game_url" value="" />
</div>

<div class="center001 mtop ">
<label  class="usernamebutton">游戏级别</label>
<select name="game_jishu" id="gjishu" value="" class="Dropbox lable05">
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
<option>6</option>
<option>7</option>
<option>8</option>
<option>9</option>
</select>(推荐栏,数字越大越靠前)
</div>

<div class="center001 mtop ">
<label class="usernamebutton ">点击次数</label>
<input class="username_inpu lable04" id="gopen" value="" type="text" name="game_open"  />(最热栏,次数越大越靠前)
</div>
<div class="center001 mtop ">
<label class="usernamebutton">新 或 热</label>
<select name="game_typeurl" id="gtypeurl" value="" class="Dropbox lable05">
<option value="xin.png">新</option>
<option value="re.png">热</option>
<option value="pu.png">普通</option>
</select>
</div>

<div class="center001 mtop ">
<button class="usernamebutton button001" type="button" onclick="login()" > 提交</button>
<button class="usernamebutton" type="button" id="reset" onclick="reset001()" >重置</button>
</div>

</div>
</div>
</form>
</body>
</html>


service代码;

@RequestMapping("/addGameSys")
public ModelAndView addGameSys(HttpServletRequest req, HttpServletResponse resp,
GameBean hear,
// gameimg为表单名。将gameimg文件表单的数据封装成CommonsMultipartFile对象    [特别注意gameimg表单名,不能和GameBean类中的名字一样。]
@RequestParam("gameimg") CommonsMultipartFile simimg)
throws Exception {
try {
// 得到上传文件名称
String simName = simimg.getOriginalFilename();
// 以当前时间毫秒数重命名文件
simName = System.currentTimeMillis()
+ simName.substring(simName.lastIndexOf("."));
// 得到指定文件的真实路径
String path = req.getSession().getServletContext()
.getRealPath("/H52/img/icon/" + simName);
// 将CommonsMultipartFile中的文件数据写入到指定文件中
simimg.getFileItem().write(new File(path));
// 将文件名存放入实体bean
hear.setGame_img(simName);
// hear.setIsimurl(simName);
// 调用业务组件保存数据
// service.add(bean);
// adminService.addHear(hear);
myBoxService.addGameBean(hear);
//System.out.println(hear.toString());
hear = null;
return new ModelAndView("H52/jumpaddGame","type",1);
} catch(Exception e) {
return new ModelAndView("H52/jumpaddGame","type",0);
}
// return new ModelAndView("H52/jumpaddGame","type",1);
}


实体bean,springmvc自动把数据封装到实体bean中

public class GameBean {
private Integer game_id;// 游戏ID
private String game_img; // icon
private String game_name; // 名
private String game_shuoMing; // 介绍
private String game_type; // 类型(下拉框选择
private String game_time; // 上线时间
private String game_url; // 路径
private String game_jishu; // 级别(1-9)数字越大越靠前(下拉框选择)
private Integer game_open; // 点击次数
private String game_opentime; // 第一次点击时间
private String game_xingurl;
private String game_reurl;
private String game_typeurl; // 图片为新或热或普通 (下拉框选择)


xml配置文件:

  <bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="UTF-8" />
<property name="maxUploadSize" value="32505856" /><!-- 上传文件大小限制为31M,31*1024*1024 -->
<property name="maxInMemorySize" value="4096" />
</bean>


完整:

Html代码

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title>文件上传</title>

<script src="static/js/jquery.min.js" type="text/javascript"></script>

<script type="text/javascript" src="static/js/jquery-form.js"></script>

<script type="text/javascript">

function subimtBtn() {

var form = $("form[name=fileForm]");

var options = {

url:'${pageContext.servletContext.contextPath}/servlet/imageUploadServlet',

type:'post',

success:function(data)

{

var jsondata = eval("("+data+")");

if(jsondata.error == "0"){

var url = jsondata.url;

alert(url)

$("#img").attr("src",url);

}else{

var message = jsondata.message;

alert(message);

}

}

};

form.ajaxSubmit(options);

//$("#fileForm").submit();

}

</script>

</head>

<body>

<div class="modal-body">

<form action='${pageContext.servletContext.contextPath}/servlet/imageUploadServlet' enctype="multipart/form-data" method="post" id="fileForm" name="fileForm">

<input type="file" name="filename">

</form>

</div>

<div class="modal-footer">

<button class="btn btn-primary" onclick="subimtBtn();">提交</button>

</div>

<div>

<img alt="img" src="" id="img">

</div>

</body>

</html>

servlet实现:imageUploadServlet.java

Java代码


package com.system.comtrol;

import java.io.File;

import java.io.IOException;

import java.io.PrintWriter;

import java.text.SimpleDateFormat;

import java.util.Arrays;

import java.util.Date;

import java.util.HashMap;

import java.util.Iterator;

import java.util.List;

import java.util.Random;

import javax.servlet.ServletException;

import javax.servlet.annotation.WebServlet;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.commons.fileupload.FileItem;

import org.apache.commons.fileupload.FileItemFactory;

import org.apache.commons.fileupload.FileUploadException;

import org.apache.commons.fileupload.disk.DiskFileItemFactory;

import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**

* Servlet implementation class ImageUploadServlet

*/

@WebServlet("/servlet/imageUploadServlet")

public class ImageUploadServlet extends HttpServlet {

private static final long serialVersionUID = 1L;

/**

* @see HttpServlet#service(HttpServletRequest request, HttpServletResponse

* response)

*/

protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

try {

PrintWriter out = response.getWriter();

// 文件保存目录路径

String savePath = request.getServletContext().getRealPath("/")+ "attached";

// 文件保存目录URL

String saveUrl = request.getContextPath() + "/attached";

// 定义允许上传的文件扩展名

HashMap<String, String> extMap = new HashMap<String, String>();

extMap.put("image", "gif,jpg,jpeg,png,bmp");

// 最大文件大小

long maxSize = 1000000;

response.setContentType("text/html; charset=UTF-8");

if (!ServletFileUpload.isMultipartContent(request)) {

out.println(getError("请选择文件。"));

return;

}

// 检查目录

File uploadDir = new File(savePath);

if (!uploadDir.isDirectory()) {

out.println(getError("上传目录不存在。"));

return;

}

// 检查目录写权限

if (!uploadDir.canWrite()) {

out.println(getError("上传目录没有写权限。"));

return;

}

String dirName = request.getParameter("dir");

if (dirName == null) {

dirName = "image";

}

if (!extMap.containsKey(dirName)) {

out.println(getError("目录名不正确。"));

return;

}

// 创建文件夹

savePath += dirName + "/";

saveUrl += dirName + "/";

File saveDirFile = new File(savePath);

if (!saveDirFile.exists()) {

saveDirFile.mkdirs();

}

SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");

String ymd = sdf.format(new Date());

savePath += ymd + "/";

saveUrl += ymd + "/";

File dirFile = new File(savePath);

if (!dirFile.exists()) {

dirFile.mkdirs();

}

FileItemFactory factory = new DiskFileItemFactory();

ServletFileUpload upload = new ServletFileUpload(factory);

upload.setHeaderEncoding("UTF-8");

List items = upload.parseRequest(request);

Iterator itr = items.iterator();

while (itr.hasNext()) {

FileItem item = (FileItem) itr.next();

String fileName = item.getName();

if (!item.isFormField()) {

// 检查文件大小

if (item.getSize() > maxSize) {

out.println(getError("上传文件大小超过限制。"));

return;

}

// 检查扩展名

String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();

if (!Arrays.<String> asList(extMap.get(dirName).split(",")).contains(fileExt)) {

out.println(getError("上传文件扩展名是不允许的扩展名。\n只允许" + extMap.get(dirName) + "格式。"));

return;

}

SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");

String newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt;

try {

File uploadedFile = new File(savePath, newFileName);

item.write(uploadedFile);

} catch (Exception e) {

out.println(getError("上传文件失败。"));

return;

}

JSONObject obj = new JSONObject();

obj.put("error", 0);

obj.put("url", saveUrl + newFileName);

out.println(obj.toString());

}

}

} catch (FileUploadException e1) {

e1.printStackTrace();

}

}

private String getError(String message) {

JSONObject obj = new JSONObject();

obj.put("error", 1);

obj.put("message", message);

return obj.toString();

}

}

项目中依赖的主要jar:commons-fileupload-1.2.jar,commons-io-1.4.jar
主要的两个js文件:jquery.min.js,jquery-form.js
这些可以去网上下载
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: