JavaWeb-表单中提交数据时到服务器有图片等文件的数据

在进行表单提交数据到服务器有文件时,需要进行的操作以及注意事项

1.注意自己的jsp文件中form表单中的属性值需要添加一项enctype="multipart/form-data"必须要加否则无法服务器无法接收,具体代码如下
<form action="${pageContext.request.contextPath }/adminUser/addGoods" method="post" enctype="multipart/form-data">
			<div>
				<h3>新增商品</h3>
			</div>
			<hr />
			<div class="row">
				<div class="col-sm-6">
					<div class="form-group form-inline">
						<label>名称:</label>
						<input type="text" name="pname" class="form-control" />
					</div>
					
					<div class="form-group form-inline">
						<label>分类:</label>
						<select name="tid" class="form-control">
							<option value="1">手机数码</option>
							<option value="2">电脑办公</option>
							<option value="3">运动户外</option>
							<option value="4">家具家居</option>
							<option value="5">鞋靴箱包</option>
							<option value="6">图书音像</option>
							<option value="7">汽车专区</option>
						</select>
					</div>
					<div class="form-group form-inline">
						<label>时间:</label>
						<input type="date" name="ptime" class="form-control" />
					</div>
				</div>
				<div class="col-sm-6">
					<div class="form-group form-inline">
						<label>价格:</label>
						<input type="text" name="pprice" class="form-control" />
					</div>
					<div class="form-group form-inline">
						<label>评分:</label>
						<input type="text" name="pstate" class="form-control" />
					</div>
				</div>
			</div>
			<div class="row">
				<div class="col-sm-10">
					<div class="form-group form-inline">
						<label>商品图片</label>
						<input type="file" name="pimage" />
					</div>
					<div class="form-group ">
						<label>商品简介</label>
						<textarea  name="pinfo" class="form-control" rows="5"></textarea>
					</div>
					<div class="form-group form-inline">
						<input type="submit" value="添加" class="btn btn-primary" />
						<input type="reset" value="重置" class="btn btn-default" />
					</div>
				</div>
			</div>
		</form>

图示:
在这里插入图片描述

2.再编写我们的Servlet代码(重点)
  1. 导入相关jar包
    在这里插入图片描述

  2. 编写文件下载的工具类

  3. 编写请求方法的代码

UploadUtils(通用代码,灵活)
package com.feilong.shop.utils;
/**
 * @author FeiLong
 * @version 1.8
 * @date 2020/9/17 16:45
 */
import java.util.Random;
import java.util.UUID;

/**
 * 文件下载工具类(安全通用)
 */
@SuppressWarnings("ALL")
public class UploadUtils {

    /**
     * 获取真实文件名
     *
     * @param name
     * @return
     */
    public static String getRealName(String name) {
        // 查找最后一个 \出现位置
        int index = name.lastIndexOf("\\");//由于一个\编译时会报错,所以两个\\进行转义
        return name.substring(index + 1);
    }

    /**
     * 获得随机UUID文件名
     *
     * @param realName
     * @return
     */

    public static String getUUIDName(String realName) {
        //获取后缀名
        int index = realName.lastIndexOf(".");
        if (index == -1) {
            return UUID.randomUUID().toString().replace("-", "").toUpperCase();
        } else {
            return UUID.randomUUID().toString().replaceAll("-", "").toUpperCase() + realName.substring(index);
        }

    }

    /**
     *  获得随机数生成二级目录
     * @return
     */
    public static String getDir() {
        String s = "0123456789ABCDEF";
        Random random = new Random();
        return "/" + s.charAt(random.nextInt(16)) + "/" + s.charAt(random.nextInt(16));
    }
}

Servlet
   public String addGoods(HttpServletRequest request, HttpServletResponse response) throws InvocationTargetException, IllegalAccessException {
        try {
            //1.创建map保存商品信息
            Map<String, Object> map = new HashMap<>();
            //2.创建磁盘文件项工厂(设置临时文件的大小和位置)
            DiskFileItemFactory factory = new DiskFileItemFactory();
            //3.创建核心上传对象
            ServletFileUpload upload = new ServletFileUpload(factory);
            //4.解析request
            List<FileItem> list = upload.parseRequest(request);
            //5.遍历list获取每一个文件项
            for (FileItem fi : list) {
                //6.获取name属性值
                String key = fi.getFieldName();
                //7.判断是否是普通的上传组件
                if (fi.isFormField()) {
                    //普通组件
                    map.put(key, fi.getString("utf-8"));
                } else {
                    //文件
                    //a.获取文件的名称
                    String name = fi.getName();
                    //b.获取文件的真实名称 1.jpg
                    String realName = UploadUtils.getRealName(name);
                    //c.获取文件的随机名称 12121212.jpg
                    String uuidName = UploadUtils.getUUIDName(realName);
                    //d.获取随机目录 /a/3
                    String dir = UploadUtils.getDir();
                    //e.获取文件内容(输入流)
                    InputStream is = fi.getInputStream();
                    //f.创建输出流
                    //获取image的真实目录
                    String imagePath = getServletContext().getRealPath("/image");
                    //创建随机目录
                    File file = new File(imagePath, dir);
                    if (!file.exists()) {
                        file.mkdirs();
                    }
                    FileOutputStream os = new FileOutputStream(new File(file, uuidName));
                    //g.对拷流
                    IOUtils.copy(is, os);
                    //h.释放资源
                    os.close();
                    is.close();
                    //i.删除临时文件
                    fi.delete();
                    //j.将商品的路径放入map中
                    map.put(key, "image" + dir + "/" + uuidName);
                }
            }
            //1.封装Product对象
            Product product = new Product();
            map.put("ptime", new Date());
            BeanUtils.populate(product, map);
            //2.调用Service层保存
            adminService.addGoods(product);
            response.getWriter().println("商品保存成功!");
            //3.重定向展示商品
            return Constants.REDIRECT + "/adminUser/showProduct";
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("商品上传失败!");
        }
    }

至此代码结束,建议先编写demo进行测试,测试成功,然后直接复制粘贴!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值