基于JavaWeb的图片上传与回显

此案例基于Servlet举例

1、前端页面

<%@ 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="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<c:if test="${empty user }">
      <%
      response.sendRedirect(request.getContextPath() + "/user?method=gotologin");
      %>
</c:if>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

 <title>欢迎页面-L-admin1.0</title>
    <link rel="shortcut icon" href="${pageContext.request.contextPath }/favicon.ico" type="image/x-icon" />
    <link rel="stylesheet" href="${pageContext.request.contextPath }/css/font.css">
    <link rel="stylesheet" href="${pageContext.request.contextPath }/css/xadmin.css">
    <link rel="stylesheet" href="${pageContext.request.contextPath }/css/checkbox_radio.css">
    <script type="text/javascript" src="${pageContext.request.contextPath }/js/jquery.min.js"></script>
    <script type="text/javascript" src="${pageContext.request.contextPath }/js/jquery-3.1.1.min.js"></script>
    <script type="text/javascript" src="${pageContext.request.contextPath }/lib/layui/layui.js" charset="utf-8"></script>
    <script type="text/javascript" src="${pageContext.request.contextPath }/js/xadmin.js"></script> 
    
    <!-- 文本框相关部件 -->
    <script type="text/javascript" src="${pageContext.request.contextPath }/wenbenkuang/js/jquery-2.1.1.min.js"></script>
    <script type="text/javascript" src="${pageContext.request.contextPath }/wenbenkuang/bootstrap-3.3.5/js/bootstrap.min.js"></script>
    <script type="text/javascript" src="${pageContext.request.contextPath }/wenbenkuang/dist/bootstrap3-wysihtml5.all.min.js"></script>
    <script type="text/javascript" src="${pageContext.request.contextPath }/wenbenkuang/dist/locales/bootstrap-wysihtml5.zh-CN.js"></script>
  </head>
  <body>
   <form method="post" enctype="multipart/form-data" action="${pageContext.request.contextPath }/goods?method=goodsadd" >
   
            
            <div style=" margin: 0 auto;width: 200px;height: 200px;text-align: center; border: 1px solid;margin-left: 150px;margin-top: 15px;">
                 <img style=" position: absolute; top: 116px;left: 251px; transform: translate(-50%,-50%);"  id="preview" onclick="AutoResizeImage(192,192,this)" src="${pageContext.request.contextPath }/images/img01.png">
            </div>
            
            
               
            <div >
                <table>
                    <tr >
                            <th style="width: 142px;">
                               
                            </th>
                            <td>
                               <input style=" margin-top: 10px;padding-left: 10px;"  type="file" accept=".jpg,.jpeg,.png,.bmp" id="goodsimg" name="goodsimg" onchange="upload(event)" required/> 
                            </td>
                    </tr> 
                    <tr >
                            <th style="width: 142px;">
                                <p style="margin-right: 10px; margin-top: 10px;font-size: 18px;font-family: 楷体;float: right;"><span style="color: red;" >*</span>所属一级分类</p>
                            </th>
                            <td>
                                <select style=" margin-top: 10px;width: 230px;height: 36px;padding-left: 10px; font-size: 16px;"  id="firstclassificationid"  name="firstclassificationid"  value="" required >	
                                    <option value="">--请选择--</option>
                                </select>
                                
                            </td>
                    </tr> 
                    <tr>
                            <th style="width: 142px;">
                                <p style="margin-right: 10px;margin-top: 10px;font-size: 18px;font-family: 楷体;float: right;"><span style="color: red;">*</span>所属二级分类</p>
                            </th>
                            <td>
                                <select style="margin-top: 10px;width: 230px;height: 36px;padding-left: 10px; font-size: 16px;"  id="twoclassificationid"  name="twoclassificationid"  value="" required >
                                    <option  value="">--请选择--</option>
                                </select>
                            </td>
                    </tr> 
                    <tr>
                            <th style="width: 142px;">
                                <p style="margin-right: 10px;margin-top: 10px;font-size: 18px;font-family: 楷体;float: right;"><span style="color: red;">*</span>物品名称</p>
                            </th>
                            <td>
                                <input style=" margin-top: 10px;width: 220px;height: 30px;padding-left: 10px; font-size: 16px;" type="text"  name="goodsname" placeholder="请输物品名称"  name="goodsname"  value="" onblur='checkName(this)' required>                                                        
				                <span id="name_msg"></span>				
             
                            </td>
                    </tr> 
                    <tr>
                            <th style="width: 142px;">
                                <p style="margin-right: 10px;margin-top: 10px;font-size: 18px;font-family: 楷体;float: right;"><span style="color: red;">*</span>物品参数信息</p>
                            </th>
                            <td>
                                <textarea class="textarea" placeholder="请输入物品参数信息 ..." value="" name="goodsinfo" style="font-family:楷体;padding-left: 10px;margin-top: 10px;width: 500px;height: 180px; font-size: 14px; line-height: 18px;" required></textarea>
                            </td>
                    </tr> 
                    <tr>
                            <th style="width: 142px;margin-top: 10px;">
                            </th>
                            <td >
                            	<label style="margin-top: 10px;font-size:22px; font-family:楷体; font-weight: 900;" class="radio"><input type="radio" name="state" value="1" checked><i class="icon-radio"></i>立即启用</label>
                            	<label style="margin-left: 30px ;margin-top: 10px;font-size:22px; font-family:楷体; font-weight: 900;"class="radio"><input type="radio" name="state" value="0" ><i class="icon-radio"></i>立即启用</label>                               
                            </td>   
                    </tr>

                </table>

                   
            </div>
            <div >
                <button style="width: 500px;margin-left: 150px ;margin-top: 10px; font-size:30px; font-family:楷体; font-weight: 900; background-color: #0dc316;" id="sub"  type="submit" > 增加 </button>
            
            
            </div>            
        </form>
        
        <!-- <p>触发:<a onclick="subform()" href="javascript:;">点击</a></p> -->
  </body>
  
  <script type="text/javascript">
  
  
  function subform(){
	  
		alert(document.getElementById("goodsimg").value);
		alert(document.getElementById("sel1").value);
		alert(document.getElementById("sel2").value);
		alert(document.getElementById("goodsname").value);
		alert(document.getElementById("goodsinfo").value);
	}



	function checksel1(obj){
		
		var val=obj.value;
		
		if(val=='0'){
			//alert(obj.value)
			document.getElementById("sel1_msg").innerHTML="<font color='red'>请选择</font>";
			document.getElementById("sub").disabled=true;
		}else{
			document.getElementById("sel1_msg").innerHTML="<font color='green'>√</font>";
			
			document.getElementById("sub").disabled=false;
			
		}
}

	//失去焦点 发送ajax
	function checkName(obj){
		//alert(obj.value)
		
		//创建核心对象
		xmlhttp=null;
		if (window.XMLHttpRequest)
		  {// code for IE7, Firefox, Opera, etc.
		  xmlhttp=new XMLHttpRequest();
		  }
		else if (window.ActiveXObject)
		  {// code for IE6, IE5
		  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
		  }
		
		//编写回调函数
		xmlhttp.onreadystatechange=function(){
			if(xmlhttp.readyState==4 && xmlhttp.status==200){
				//xmlhttp.responseText;
				if(xmlhttp.responseText==1){
					document.getElementById("name_msg").innerHTML="<font color='green'>物品名未被添加</font>";
					
					document.getElementById("sub").disabled=false;
				}else{
					document.getElementById("name_msg").innerHTML="<font color='red'>物品名已存在</font>";
					document.getElementById("sub").disabled=true;
					
				}
			}
		}
		
		//open操作
		xmlhttp.open("post","${pageContext.request.contextPath}/goods?method=findname&goodsname="+obj.value);
		
		//send
		xmlhttp.send();
	}

  
  //只要DOM就绪就会执行,进行异步处理    
  $(document).ready(function(){
      //声明一个全局变量,保存执行异步后获取的map对象
      var FIRSTDATE = null;

      $.ajax({
          type: "GET",
          url:"${pageContext.request.contextPath }/goods?method=getClass",
          dataType:"json",
          success: function (firstdata) {
              //将获取的值赋值给全局变量,因为这个返回的对象要在一级菜单改变时使用,
              //所以需要扩大他的范围
              FIRSTDATE = firstdata;
              //输出打印
              console.log(firstdata);
              var grade=$("#firstclassificationid");
              for(var key in firstdata){
                  //输出打印
                  console.log("属性:" + key + "====================");
                  //根据key去取值,获得List对象
                  var list = firstdata[key];
                  //遍历这个List对象
                  for(var j = 0; j < list.length; j++){
                      var obj = list[j];
                      //一会在下面控制器代码中可以看的出来,保存map对象时,
                      //一级菜单保存的key值为0
                      //二级菜单保存为0_...
                      if(key=="0"){
                          console.log(obj);
                          //添加一级下拉菜单
                          grade.append("<option value="+obj.id+">"+obj.firstclassificationname+"</option>"); 
                      }else{
                          console.log(obj);
                      }
                  }
              }
          },
          error: function (firstdata) {
              console.log("失败")
          }
      });

      //一级菜单的改变事件
      $("#firstclassificationid").change(function(){
          var str = $("#firstclassificationid").val();
          $("#twoclassificationid").empty();
          $("#twoclassificationid").append("<option value=''>--请选择--</option>");
          if(str != "null"){
              //遍历全局变量
              for(var key in FIRSTDATE){
                  var list = FIRSTDATE[key];
                  for(var j = 0; j < list.length; j++){
                      var obj = list[j];
                      //判断并填充值
                      if(key!="0" && key=="1"+ str){
                          //输出打印
                          console.log(obj);
                          //添加二级下拉菜单
                          $("#twoclassificationid").append("<option value="+obj.id+">"+obj.twoclassificationname+"</option>"); 
                      }
                  }
              }
          }
      }); 

  });

  
  
        function upload(event){
             var inputs = event.target.files[0];
            //方法一:
            //  var img=window.URL.createObjectURL(inputs)
            //  var size=img.filesize
            //  //回显图片
            //  document.getElementById("preview").setAttribute("src",img)
             
     
            //方法二:
             var reader = new FileReader()
             reader.readAsDataURL(inputs)
             reader.onload = function(){ //当读取操作成功时调用
             document.getElementById("preview").setAttribute("src",this.result)
             console.log(new Blob([this.result]))
             }
        }; 
    
        function AutoResizeImage(maxWidth,maxHeight,objImg){
            var img = new Image();
            img.src = objImg.src;
            var hRatio;
            var wRatio;
            var Ratio = 1;
            var w = img.width;
            var h = img.height;
            wRatio = maxWidth / w;
            hRatio = maxHeight / h;
            if (maxWidth ==0 && maxHeight==0){
            Ratio = 1;
            }else if (maxWidth==0){//
            if (hRatio<1) Ratio = hRatio;
            }else if (maxHeight==0){
            if (wRatio<1) Ratio = wRatio;
            }else if (wRatio<1 || hRatio<1){
            Ratio = (wRatio<=hRatio?wRatio:hRatio);
            }
            if (Ratio<1){
            w = w * Ratio;
            h = h * Ratio;
            }
            objImg.height = h;
            objImg.width = w;
            }
    </script>
</html>         

2、后端代码

(1)GoodsServlet

/* 增加物品信息 */
	public String goodsadd(HttpServletRequest request, HttpServletResponse response) throws Exception {
		/* 获取系统当前时间 */
		Date date = new Date();
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String dateString = formatter.format(date);

		/* 获取Session中用户信息 */
		User user = (User) request.getSession().getAttribute("user");
		try {
			/* 创建map 放入前台传递的数据 */
			HashMap<String, Object> map = new HashMap<>();
			/* 创建全局文件项变量imgFile */
			FileItem imgFile = null;
			/* 创建对象goods */
			Goods goods = new Goods();
			/* 创建磁盘文件项 */
			DiskFileItemFactory factory = new DiskFileItemFactory();
			/* 创建核心上传对象 */
			ServletFileUpload upload = new ServletFileUpload(factory);
			/* 解析request */
			List<FileItem> list = upload.parseRequest(request);
			/* 遍历集合 */
			for (int i = 0; i < list.size(); i++) {
				/* 创建变量fi */
				FileItem fi = list.get(i);
				/* 判断是否是普通的上传组件 */
				if (fi.isFormField()) {
					/* 获取普通上传组件内容并放入map */
					map.put(fi.getFieldName(), fi.getString("utf-8"));
				} else {
					/* 获取文件名称 */
					String name = fi.getName();
					/* 获取文件的真实名称 xxxx.xx */
					String realName = UploadUtils.getRealName(name);
					/* 判断文件真实名是否存在 */
					if (realName != null && realName != "") {
						/* 赋值给全局变量imgFile */
						imgFile = fi;
					} else {
						/* 当文件名为空的时候,返回上一步,并提示相关信息 */
						response.setContentType("text/html; charset=UTF-8");
						PrintWriter out = response.getWriter();
						out.println("<script language = javascript>alert('请选择图片,不允许为空!')");
						out.println("window.history.go(-1)</script>");
						out.close();
					}
				}

			}
			/* 封装参数 */
			BeanUtils.populate(goods, map);
			/* 获取文件流 */
			InputStream is = imgFile.getInputStream();
			/* 获取原始文件名 */
			String fileName = imgFile.getName();
			/* 获取文件后缀名即文件类型 */
			String type = fileName.substring(fileName.lastIndexOf(".") + 1);
			/* 凭接保存上传文件的文件名 */
			String saveName = goods.getGoodsname() + "【" + UUIDUtils.getId() + "】" + "." + type;
			/* 获取UploadUtils中封装的文件保存路径 */
			String path = UploadUtils.getPath();
			/* 保存图片 */
			FileOutputStream os = new FileOutputStream(new File(path, saveName));
			IOUtils.copy(is, os);
			/* 关闭文件流 */
			os.close();
			is.close();
			/* 删除临时文件 */
			imgFile.delete();

			/* 根据已封装到goods的twoclassificationid获取隶属的一级和二级分类名 */
			/* 调用TwoclassificationService */
			TwoclassificationService twoclass = new TwoclassificationServiceImpl();
			/* 获取已封装到goods的twoclassificationid并赋值给变量id */
			String id = goods.getTwoclassificationid();
			/* 根据twoclassificationid查询出一条twoclassification信息 */

			Twoclassification twoclassification = twoclass.finById(id);
			if (twoclassification == null) {
				/* 页面重定向 */
				response.setContentType("text/html; charset=UTF-8");
				PrintWriter out = response.getWriter();
				out.println("<script language = javascript>alert('二级分类不允许为空!')");
				out.println("window.history.go(-1)</script>");
				out.close();
			} else {

				FirstclassificationService fct = new FirstclassificationServiceImpl();
				Firstclassification firstclassification = fct.finById(goods.getFirstclassificationid());

				goods.setFirstclassification(firstclassification);
				goods.setTwoclassification(twoclassification);
				goods.setFirstclassificationname(firstclassification.getFirstclassificationname());
				goods.setTwoclassificationname(twoclassification.getTwoclassificationname());
				/* 设置物品的ID */
				goods.setId(UUIDUtils.getId());
				/* 设置物品隶属的一级分类名 */
				// goods.setFirstclassificationname(twoclassification.getFirstclassificationname());
				/* 设置物品隶属的二级分类名 */
				// goods.setTwoclassificationname(twoclassification.getTwoclassificationname());
				/* 设置添加物品操作用户 */
				goods.setCreateuser(user.getUsername());
				/* 设置添加物品照片的保存路径以及保存的文件名 */
				goods.setGoodsimg("/images/" + saveName);
				/* 设置创建时间 */
				goods.setCreatetime(dateString);
				/* 设置修改时间 */
				goods.setUpdatetime(dateString);
				/* 调用GoodServer */
				GoodsService g = new GoodsServiceImpl();

				/* 执行goodsadd方法实现添加物品的保存 */
				g.goodsadd(goods);

				/* 添加系统日志 */
				SystemlogService log = new SystemlogServiceImpl();
				Systemlog systemlog = new Systemlog();
				/* 获取操作者IP */
				String remoteIp = request.getRemoteAddr();
				/* 设置当前操作的系统日志内容开始 */
				// 设置随机ID
				systemlog.setId(UUIDUtils.getId());
				// 设置IP
				systemlog.setOperationip(remoteIp);
				// 设置操作用户名
				systemlog.setOperationuser(user.getUsername());
				// 设置操作类型
				systemlog.setOperationtype("添加物品");
				// 设置操作内容
				systemlog.setOperationcontent(
						user.getUsername() + "用户于" + dateString + "成功添加名为:" + goods.getGoodsname() + "的物品");
				// 设置操作时间
				systemlog.setOperationtime(dateString);
				/* 设置当前操作的系统日志内容结束 */
				/* 执行添加操作,增加系统日志 */
				log.add(systemlog);

				/* 页面重定向 */
				response.setContentType("text/html; charset=UTF-8");
				PrintWriter out = response.getWriter();
				out.println("<script language = javascript>alert('物品添加成功!')");
				out.println("window.history.go(-1)</script>");
				out.close();
			}

		} catch (Exception e) {
			e.printStackTrace();
			/* 页面重定向 */
			/* 添加系统日志 */
			SystemlogService log = new SystemlogServiceImpl();
			Systemlog systemlog = new Systemlog();
			/* 获取操作者IP */
			String remoteIp = request.getRemoteAddr();
			/* 设置当前操作的系统日志内容开始 */
			// 设置随机ID
			systemlog.setId(UUIDUtils.getId());
			// 设置IP
			systemlog.setOperationip(remoteIp);
			// 设置操作用户名
			systemlog.setOperationuser(user.getUsername());
			// 设置操作类型
			systemlog.setOperationtype("添加物品");
			// 设置操作内容
			systemlog.setOperationcontent(user.getUsername() + "用户于" + dateString + "执行添加物品操作失败");
			// 设置操作时间
			systemlog.setOperationtime(dateString);
			/* 设置当前操作的系统日志内容结束 */
			/* 执行添加操作,增加系统日志 */
			log.add(systemlog);

			response.setContentType("text/html; charset=UTF-8");
			PrintWriter out = response.getWriter();
			out.println("<script language = javascript>alert('物品添加失败!')");
			out.println("window.history.go(-1)</script>");
			out.close();

		}
		return null;
	}

(2)GoodsService

void goodsadd(Goods goods) throws Exception;

(3) GoodsServiceImpl

public void goodsadd(Goods goods) throws Exception {
		GoodsDao dao = new GoodsDaoImpl();
		dao.goodsadd(goods);

	}

(4)GoodsDao

	void goodsadd(Goods goods) throws Exception;

(5) GoodsDaoImpl

public void goodsadd(Goods goods) throws Exception {
		QueryRunner qr = new QueryRunner(DataSourceUtils.getDataSource());
		String sql = "INSERT INTO `s_goods` VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
		qr.update(sql, goods.getId(), goods.getFirstclassification().getId(), goods.getTwoclassification().getId(),
				goods.getGoodsname(), null, goods.getGoodsimg(), goods.getGoodsinfo(), goods.getState(),
				goods.getCreateuser(), goods.getCreatetime(), goods.getUpdatetime(), null, null, null);

	}

3、数据库

CREATE TABLE `s_goods` (
  `id` varchar(32) NOT NULL,
  `firstclassificationid` varchar(32) NOT NULL COMMENT '一级分离ID',
  `twoclassificationid` varchar(32) NOT NULL COMMENT '二级分类ID',
  `goodsname` varchar(255) DEFAULT NULL COMMENT '物品名',
  `goodscode` varchar(20) DEFAULT NULL COMMENT '物品标编码',
  `goodsimg` varchar(255) DEFAULT NULL COMMENT '物品图片',
  `goodsinfo` varchar(5000) DEFAULT NULL COMMENT '物品信息',
  `state` varchar(5) DEFAULT NULL COMMENT '状态(1启用,0停用)',
  `createuser` varchar(255) DEFAULT NULL COMMENT '创建人',
  `createtime` varchar(255) DEFAULT NULL COMMENT '创建时间',
  `updatetime` varchar(255) DEFAULT NULL COMMENT '修改时间',
  `goods1` varchar(255) DEFAULT NULL,
  `goods2` varchar(255) DEFAULT NULL,
  `goods3` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `fid` (`firstclassificationid`),
  KEY `tid` (`twoclassificationid`),
  CONSTRAINT `fid` FOREIGN KEY (`firstclassificationid`) REFERENCES `s_firstclassification` (`id`),
  CONSTRAINT `tid` FOREIGN KEY (`twoclassificationid`) REFERENCES `s_twoclassification` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
package www.chenqiang.top.domain;

public class Goods {
	/*
	 * `id` varchar(32) NOT NULL, `firstclassificationid` varchar(32) DEFAULT NULL
	 * COMMENT '一级分离ID', `firstclassificationname` varchar(255) DEFAULT NULL COMMENT
	 * '一级分类名', `twoclassificationid` varchar(32) DEFAULT NULL COMMENT '二级分类ID',
	 * `twoclassificationname` varchar(255) DEFAULT NULL COMMENT '二级分类名',
	 * `goodsname` varchar(255) DEFAULT NULL COMMENT '物品名', `goodsimg` varchar(255)
	 * DEFAULT NULL COMMENT '物品图片', `goodsinfo` varchar(5000) DEFAULT NULL COMMENT
	 * '物品信息', `state` varchar(5) DEFAULT NULL COMMENT '状态(1启用,0停用)', `createuser`
	 * varchar(255) DEFAULT NULL COMMENT '创建人', `createtime` varchar(255) DEFAULT
	 * NULL COMMENT '创建时间', `updatetime` varchar(255) DEFAULT NULL COMMENT '修改时间',
	 * `goods1` varchar(255) DEFAULT NULL, `goods2` varchar(255) DEFAULT NULL,
	 * `goods3` varchar(255) DEFAULT NULL,
	 */

	private String id;
	private String firstclassificationid;

	private Firstclassification firstclassification;// 物品和一级分类多对一
	private String firstclassificationname;// 一级分类名,便于打印
	private Twoclassification twoclassification;// 物品和二级分类多对一
	private String twoclassificationname;// 二级分类名,便于打印

	private String twoclassificationid;
	private String goodsname;
	private String goodscode;

	private String goodsimg;
	private String goodsinfo;
	private String state;

	private String createuser;
	private String createtime;
	private String updatetime;

	private String goods1;
	private String goods2;
	private String goods3;

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getFirstclassificationid() {
		return firstclassificationid;
	}

	public void setFirstclassificationid(String firstclassificationid) {
		this.firstclassificationid = firstclassificationid;
	}

	public String getFirstclassificationname() {
		return firstclassificationname;
	}

	public void setFirstclassificationname(String firstclassificationname) {
		this.firstclassificationname = firstclassificationname;
	}

	public String getTwoclassificationid() {
		return twoclassificationid;
	}

	public void setTwoclassificationid(String twoclassificationid) {
		this.twoclassificationid = twoclassificationid;
	}

	public String getTwoclassificationname() {
		return twoclassificationname;
	}

	public void setTwoclassificationname(String twoclassificationname) {
		this.twoclassificationname = twoclassificationname;
	}

	public String getGoodsname() {
		return goodsname;
	}

	public void setGoodsname(String goodsname) {
		this.goodsname = goodsname;
	}

	public String getGoodsimg() {
		return goodsimg;
	}

	public void setGoodsimg(String goodsimg) {
		this.goodsimg = goodsimg;
	}

	public String getGoodsinfo() {
		return goodsinfo;
	}

	public void setGoodsinfo(String goodsinfo) {
		this.goodsinfo = goodsinfo;
	}

	public String getState() {
		return state;
	}

	public void setState(String state) {
		this.state = state;
	}

	public String getCreateuser() {
		return createuser;
	}

	public void setCreateuser(String createuser) {
		this.createuser = createuser;
	}

	public String getCreatetime() {
		return createtime;
	}

	public void setCreatetime(String createtime) {
		this.createtime = createtime;
	}

	public String getUpdatetime() {
		return updatetime;
	}

	public void setUpdatetime(String updatetime) {
		this.updatetime = updatetime;
	}

	public String getGoods1() {
		return goods1;
	}

	public void setGoods1(String goods1) {
		this.goods1 = goods1;
	}

	public String getGoods2() {
		return goods2;
	}

	public void setGoods2(String goods2) {
		this.goods2 = goods2;
	}

	public String getGoods3() {
		return goods3;
	}

	public void setGoods3(String goods3) {
		this.goods3 = goods3;
	}

	public Firstclassification getFirstclassification() {
		return firstclassification;
	}

	public void setFirstclassification(Firstclassification firstclassification) {
		this.firstclassification = firstclassification;
	}

	public Twoclassification getTwoclassification() {
		return twoclassification;
	}

	public void setTwoclassification(Twoclassification twoclassification) {
		this.twoclassification = twoclassification;
	}

	public String getGoodscode() {
		return goodscode;
	}

	public void setGoodscode(String goodscode) {
		this.goodscode = goodscode;
	}
}

以下是一个简单的JavaWeb图片上传回显的JSP和Servlet的完整代码: 1. JSP 文件代码: ``` <!DOCTYPE html> <html> <head> <title>Image Upload and Display</title> </head> <body> <h1>Image Upload and Display</h1> <form action="ImageUploadServlet" method="post" enctype="multipart/form-data"> <input type="file" name="file" /><br/><br/> <input type="submit" value="Upload" /> </form> <br/><br/> <% if(request.getAttribute("imagePath") != null) { %> <img src="<%= request.getContextPath() %>/<%= request.getAttribute("imagePath") %>" /> <% } %> </body> </html> ``` 2. Servlet 文件代码: ``` import java.io.File; import java.io.IOException; import java.util.UUID; import javax.servlet.ServletException; import javax.servlet.annotation.MultipartConfig; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.Part; @WebServlet("/ImageUploadServlet") @MultipartConfig(fileSizeThreshold=1024*1024*2, maxFileSize=1024*1024*10, maxRequestSize=1024*1024*50) public class ImageUploadServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String imagePath = null; String appPath = request.getServletContext().getRealPath(""); String savePath = appPath + File.separator + "uploads"; File fileSaveDir = new File(savePath); if (!fileSaveDir.exists()) { fileSaveDir.mkdir(); } for (Part part : request.getParts()) { String fileName = extractFileName(part); if (fileName != null && !fileName.equals("")) { String extension = fileName.substring(fileName.lastIndexOf(".")); String uuid = UUID.randomUUID().toString(); imagePath = "uploads" + File.separator + uuid + extension; part.write(savePath + File.separator + uuid + extension); } } request.setAttribute("imagePath", imagePath); request.getRequestDispatcher("index.jsp").forward(request, response); } private String extractFileName(Part part) { String contentDisp = part.getHeader("content-disposition"); String[] items = contentDisp.split(";"); for (String s : items) { if (s.trim().startsWith("filename")) { return s.substring(s.indexOf("=") + 2, s.length()-1); } } return null; } } ``` 在这个例子中,我们使用了Servlet 3.0的@MultipartConfig注解来处理文件上传。这个注解告诉容器这个Servlet将会接收multipart/form-data类型的请求,并且指定了上传文件的大小限制。在doPost()方法中,我们首先获取应用程序的根目录,并且创建一个名为“uploads”的文件夹来保存上传的文件。然后,我们遍历所有的文件部件,提取文件名,并且生成一个唯一的UUID和文件扩展名的组合作为文件名。最后,我们将文件保存到uploads文件夹中,并且将图片路径作为请求属性存储,并且转发到JSP页面以显示上传的图片。 请注意,这里的示例代码仅供参考,您需要根据自己的需求进行修改和调整。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

我若心飞扬,天地任我逍遥

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值