SSM——SpringMVC文件图片上传

1.pox.xml 中导入依赖

<!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
    <dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.4</version>
    </dependency>

2.创建表单

  <form action="${pageContext.request.contextPath}/user/upload" method="post" enctype="multipart/form-data">
        <input type="file" name="imgFile"/>
        <br/>
        <input type="submit" value="上传">
    </form>

3.创建 Controller

@Controller
@RequestMapping(/user)
public class UploadController {
   
     // SpringMVC 文件上传  MultipartFile对象
     
    @RequestMapping("/upload")
    public String upload(MultipartFile imgFile) throws IOException {
    
        //设置上传路径
        String path="E:/upload";
        File targetFile=new File(path);
        
        //如果文件夹不存在就创建文件夹 mkdirs()
        if(!targetFile.exists()){
            targetFile.mkdirs();
        }
        
        
        //获取文件原始名
        String fileName=imgFile.getOriginalFilename();
 
        //获取文件后缀名
        String type=fileName.substring(fileName.lastIndexOf("."),fileName.length());
        
        //使用UUID,并把 - 去掉,防止文件名重合,保证文件名唯一
        fileName= UUID.randomUUID().toString().replace("-","").toLowerCase()+type;
        
        //后台打印查看,可不写
        System.out.println(fileName);
        
        //上传文件: transferTo()
        imgFile.transferTo(new File(targetFile,fileName));

		//返回前端页面
        return  "success";
    }
}

  1. Springmvc.xml中设置文件解析器
			<!--配置文件解析器-->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!--设置上传文件的大小  单位是字节 设置为 10M 可改-->
        <property name="maxUploadSize" value="10485760"></property>

    </bean>

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值