javaweb电子商城上传图片的问题

本文详细介绍了一种在JSP环境中实现图片上传的方法,包括使用ServletFileUpload解析multipart请求、生成随机文件名和目录,以及将图片保存到服务器的具体步骤。

在进行图片上传的时候,首先必须明确在jsp界面

method="post" enctype="multipart/form-data" 

先贴工具类

package com.itheima.utils;

import java.util.UUID;

public class FileUploadUtils {

	public static String subFileName(String fileName) {
		// 查找最后一个 \出现位置
		int index = fileName.lastIndexOf("\\");
		if (index == -1) {
			return fileName;
		}
		return fileName.substring(index + 1);
	}

	// 获得随机UUID文件名
	public static String generateRandonFileName(String fileName) {
		// 获得扩展名
		int index = fileName.lastIndexOf(".");
		if (index != -1) {
			String ext = fileName.substring(index);
			return UUID.randomUUID().toString() + ext;
		}
		return UUID.randomUUID().toString();
	}

	// 获得hashcode生成二级目录
	public static String generateRandomDir(String uuidFileName) {
		int hashCode = uuidFileName.hashCode();
		// 一级目录
		int d1 = hashCode & 0xf;
		// 二级目录
		int d2 = (hashCode >> 4) & 0xf;
		return "/" + d1 + "/" + d2;
	}
}

具体实现:

@WebServlet("/adminProduct")
public class AddProductServlet extends HttpServlet {

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


        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");

        response.setContentType("text/html;charset=UTF-8");
        DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
        diskFileItemFactory.setSizeThreshold(1024 * 1024 * 10);
        //使用factory的缓冲区和临时文件
        ServletFileUpload upload = new ServletFileUpload(diskFileItemFactory);
        upload.setHeaderEncoding("utf-8");
        List<FileItem> fileItems = null;
        Product product = new Product();
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            //获得表单中提交的数据(为List集合)
            fileItems = upload.parseRequest(request);
            Iterator it = fileItems.iterator();
            for (FileItem item : fileItems) {
                if (item.isFormField()) {
                    //判断input是否为普通表单输入项
                    String name = item.getFieldName();
                    String value = item.getString("utf-8");

                    map.put(name, value);
                    System.out.println(map);

                } else {
                    String filename = item.getName();

                    String randomName = FileUploadUtils
                            .generateRandonFileName(filename);

                    String randomDir = FileUploadUtils
                            .generateRandomDir(randomName);

                    String imgurl_parent = "productImg" + randomDir;

                    File parentDir = new File(this.getServletContext()
                            .getRealPath(imgurl_parent));

                    if (!parentDir.exists()) {
                        parentDir.mkdirs();
                    }
                    String pimage = imgurl_parent + "/" + randomName;

                    System.out.println(pimage);

                    map.put("pimage", pimage);

                    IOUtils.copy(item.getInputStream(), new FileOutputStream(
                            new File(parentDir, randomName)));
                    item.delete();

                }

            }

            product.setPdate(new Date());

            product.setPid(UUIDUtils.getUUID());//我这里是为了存随机id可以去掉
            BeanUtils.populate(product, map);

            ProductService productService = new ProductService();
            productService.addProduct(product);
            //注意这里要跳到ProductFindAllServlet,这个Servlet再进行查询显示到product_list.jsp
            request.getRequestDispatcher("/productList").forward(request, response);
            System.out.println("进行添加了吗");

        } catch (FileUploadException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }

 

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

特立独行的蜗牛

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

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

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

打赏作者

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

抵扣说明:

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

余额充值