使用SSM框架实现文件上传

本文介绍了一个使用Spring框架实现的商品图片上传功能,包括前端文件选择输入框配置与后端图片处理逻辑。通过生成唯一文件名并按日期组织目录,确保了图片的有效管理和快速检索。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前端jsp代码

<input type="file" name="file" id="input_file" style="display:inline;" required="required"> ( 推荐尺寸: 500 * 500 )

后端代码

package com.hopu.controller;

import com.github.pagehelper.PageInfo;
import com.hopu.bean.Admins;
import com.hopu.bean.Goods;
import com.hopu.bean.PageBean;
import com.hopu.service.AdminService;

import com.hopu.util.UUIDUtil;
import com.sun.xml.internal.ws.util.JAXWSUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/admin")
public class AdminController {
    @Autowired
    private AdminService adminService;
 

    //商品添加
    @RequestMapping("/goodSave")
    public String goodSave(Goods goods, MultipartFile file, HttpServletRequest request) throws IOException {
        System.out.println(goods);
        //1,生成文件上传的路径
        String realPath = request.getSession().getServletContext().getRealPath("upload");
        System.out.println("realPath = " + realPath);
        //生成带日期的文件夹名
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String dateFile = sdf.format(new Date());
        System.out.println("dateFile = " + dateFile);
        
        realPath = realPath+"/"+dateFile;
        //判断该文件夹是否存在,
        System.out.println("uploadd = " + realPath);
        //判断文件是否存在
        File uploadFile = new File(realPath);
        System.out.println("uploadFile = " + uploadFile);
        if(!uploadFile.exists()){
            uploadFile.mkdirs();
        }
        //图片生成32位随机数
        String str = file.getOriginalFilename();
        System.out.println("str = " + str);
        String name =   UUIDUtil.getUUID()+str.substring(str.lastIndexOf("."));

        //2,创建要上传的文件对象
        File upFile = new File(uploadFile,name);
        //3,上传文件
        file.transferTo(upFile);
        
        //4.获取文件的相对路径
        String cover ="../upload/"+dateFile+"/"+name;
        goods.setCover(cover);
        System.out.println("goods = " + goods);
        //5.保存数据
        adminService.uploadadd(goods);
        return  "forward:goodList";
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Vue1024

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

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

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

打赏作者

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

抵扣说明:

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

余额充值