IntelliJ IDEA 实现商品图片上传及其他商品信息保存的代码

在网上搜了下idea上传图片的程序,但大部分都是myeclips的或者代码程序有误,因此自己就写一篇博客与大家分享,话不多说,直接程序走起!

第一步:配置pom.xml中上传文件所需的依赖,代码如下

<!--		下面是文件上传需要的依赖 开始处-->
		<dependency>
			<groupId>commons-io</groupId>
			<artifactId>commons-io</artifactId>
			<version>2.4</version>
		</dependency>
		<dependency>
			<groupId>commons-fileupload</groupId>
			<artifactId>commons-fileupload</artifactId>
			<version>1.3.1</version>
		</dependency>
<!--        上面是文件上传需要的依赖 结尾处-->

第二步:创建商品实体

/**
 * @Author: Wxz
 * @Date: 2020/8/23 18:03
 */
@Data
@Entity
@TableName("t_product")
public class FoodEntity {
    /**
     * 商品ID
     */
    @TableId
    private String id;

    /**
     *商品(食品)名称
     */
    private String foodName;

    /**
     * 商品(食品)图片路径
     */
    private String foodImaUrl;

    /**
     * 商品(菜品)价格
     */
    private double foodPrice;

    /**
     * 菜品的创建时间
     */
    private LocalDateTime createTime;

    /**
     * 下面的是文件上传必须有的一个字段,file名字要与form表单中的名字一致
     */
    private MultipartFile file;

}

第三步:创建Dao


/**
 * @Author: Wxz
 * @Date: 2020/8/23 18:36
 */

@Repository
@Mapper
public interface FoodDao {

    /**
     *商品列表查询
     * @param page
     * @param param
     */
    IPage<FoodEntity> findPage(IPage<FoodEntity> page, @Param("param") Map<String, Object> param);

    /**
     * 新增商品
     * @param foodentity
     * @return
     */
    boolean addFood(FoodEntity foodentity);

}

第四步:创建service

/**
 * @Author: Wxz
 * @Date: 2020/8/23 18:55
 */
public interface FoodService{

    /**
     * 商品列表查询 (分页版)
     * @param  queryParam
     * @param currentFood
     */
    PageResult<FoodEntity> findPage(QueryParam queryParam, FoodEntity currentFood);

    /**
     * 新增商品
     * @param foodEntity
     */
    ResponseResult addFood(FoodEntity foodEntity);

}

第五步:创建service实现类

/**
 * @Author: Wxz
 * @Date: 2020/8/23 19:01
 */

@Service
@Slf4j
public class FoodServiceImpl implements FoodService {
    /**
     * 注入foodDao
     */
    @Autowired
    protected FoodDao foodDao;

    /**
     * 商品列表查询
     * @param  queryParam
     * @param currentFood
     * @return
     */
    @Override
    public PageResult<FoodEntity> findPage(QueryParam queryParam, FoodEntity currentFood) {
        Map<String, Object> param = queryParam.toMap();
        IPage<FoodEntity> page = foodDao.findPage(queryParam.toPage(), param);
        return new PageResult<>(page);
    }

    /**
     * 增加商品
     * @param foodEntity
     * @return
     */
    @Override
    public ResponseResult addFood( FoodEntity foodEntity) {
        ResponseResult result = new ResponseResult();
        try{
            //设定创建者ID为1
            foodEntity.setCreateId(1);
           //下面的代码是设置当前时间的
            foodEntity.setCreateTime(LocalDateTime.now());
            boolean returnMark = foodDao.addFood(foodEntity);
            if (returnMark) {
                result.setMsg("操作成功!");
                return result;
            }
            result.setResultCode(ResultCode.RESULT_FAIL);
            result.setMsg("操作失败!");
            return result;
        }catch (Exception e) {
            log.error("when add food", e);
            result.setResultCode(ResultCode.RESULT_FAIL);
            result.setMsg("操作失败!");
            return result;
        }
    }

第六步:创建controller

/**
 * @Author: Wxz
 * @Date: 2020/8/23 20:07
 */
@Slf4j
@RestController
@RequestMapping("food")
@CrossOrigin
public class FoodController {
    /**
     * 添加依赖
     */
    @Autowired
    private FoodService foodService;

    /**
     * 菜品管理-菜品信息列表管理
     * @param queryParam
     * @param food
     * @return
     */
    @CrossOrigin
    @SystemLog(module = "菜品管理",operation = "菜品信息列表查询")
    @PostMapping(value = "queryFoodPagelist", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public PageResult<FoodEntity> queryFoodPagelist(@RequestBody QueryParam queryParam,FoodEntity food){
        PageResult<FoodEntity> pageresult = foodService.findPage(queryParam, food);
        return pageresult;
    }

    /**
     * 菜品管理-新增菜品
     * @param food
     * @return
     */
    @CrossOrigin
    @SystemLog(module = "菜品管理",operation = "新增菜品")
    @PostMapping(value = "addFood", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResponseResult addFood(FoodEntity food, MultipartFile file, HttpServletRequest request) throws IOException {
        //设置图片上传路径,是目标文件夹的路径
//        String filePath = request.getSession().getServletContext().getRealPath("/upload");
        String filePath ="D:\\File\\";
        System.out.println("filePath:::"+filePath);

        // 获取原始图片的扩展名
        String originalFilename = file.getOriginalFilename();
        System.out.println("originalFilename:::"+originalFilename);
        // 生成文件新的名字
        String newFileName = UUID.randomUUID().toString().replaceAll("-", "") + originalFilename;
        System.out.println("newFileName:::"+newFileName);

        // 封装上传文件位置的全路径
        File targetFile = new File(filePath, newFileName);
        file.transferTo(targetFile);

        //将上传图片的名字保存到数据库
        food.setFoodImaUrl(filePath+newFileName);

        //返回保存的数据
        return foodService.addFood(food);

    }

}

第七步:设置mapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.example.orderserver.dao.foodManage.FoodDao">
<!--    菜品的列-->
    <sql id="FoodColume">
        <trim suffix="" suffixOverrides=",">
            <if test="id != null">
                id,
            </if>
            <if test="createId != null">
                createId,
            </if>
            <if test="foodName != null">
                foodName,
            </if>
            <if test="foodImaUrl != null">
                foodImaUrl,
            </if>
         
        </trim>
    </sql>
<!--    菜品需要传的值-->
    <sql id="FoodValue">
        <trim suffix="" suffixOverrides=",">
            <if test="id != null">
                #{id},
            </if>
            <if test="createId != null">
                #{createId},
            </if>
            <if test="foodName != null">
                #{foodName},
            </if>
            <if test="foodImaUrl != null">
                #{foodImaUrl},
            </if>
        </trim>
    </sql>
    <select id="findPage" resultType="com.example.orderserver.entity.foodManage.FoodEntity">
        select f.id, f.createId, f.foodName, f.foodImaUrl,
        f.createTime from t_product f
    </select>

    <!-- 添加商品信息 -->
    <insert id="addFood" parameterType="com.example.orderserver.entity.foodManage.FoodEntity">
        INSERT INTO
        t_product(
        <include refid="FoodColume"/>
        )
        VALUES(
        <include refid="FoodValue"/>
        )
    </insert>

第八步:前端html页面编写

<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
    <script src="https://cdn.staticfile.org/axios/0.18.0/axios.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <style type="text/css">
        * {
            margin: 0px;
            padding: 0px;
        }
    </style>
</head>
<body>
<div id="app">
    <form action="自己请求的路径" method="post" enctype="multipart/form-data">
        菜品ID:<input type="text" name="id"><br>
        菜品名称:<input type="text" name="foodName"><br>
        菜品价格:<input type="text" name="foodPrice"><br>
        图片:<input type="file" name="file"><br>
        <input type="submit" value="提交">
    </form>
</div>
</body>
</html>

第九步:数据库表

第十步:启动项目,最后成功实现商品图片的上传以及信息的保存

大家如果有什么不懂的地方请留言哈

  • 1
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值