SpringMVC实现文件上传

SpringMVC实现文件上传

代码逻辑:
在这里插入图片描述

1、导入关于文件上传的jar包
在这里插入图片描述
2、给出 web.xml 和 success.jsp
3、给出前端代码

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>主页</title>
    
</head>
<body>

    <h3>文件上传</h3>

       
    <form action="${pageContext.request.contextPath}/file/upload" enctype="multipart/form-data" method="post">
	  	 名称:<input type="text" name="picName"><br>
	         文件:<input type="file" name="uploadFile"><br>
	    <input type="submit" value="上传">
	</form>

	  
</body>
</html>

4、给出控制器代码


import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Controller;
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 java.io.File;
import java.util.UUID;

@Controller
@RequestMapping("/file")
public class FileuploadController {
    @RequestMapping("/upload")
    public String pictureUpload(String picName, @RequestParam("uploadFile") MultipartFile uploadFile, HttpServletRequest request) throws Exception {
        System.out.println("picName= " + picName); //普通域

        //处理文件
        String _path = request.getServletContext().getRealPath("/");//项目的部署目录
        File path = new File(_path, "/upload");
        if (!path.exists()) {
            path.mkdirs();
        }

        System.out.println(path);
        
        //处理文件名重复
        String fileName = uploadFile.getOriginalFilename();//上传的文件名"logo.jpg" "logo-随机数.jpg"
        fileName = FilenameUtils.getBaseName(fileName) + "-" + UUID.randomUUID().toString().replaceAll("-","") + "." + FilenameUtils.getExtension(fileName);

        //上传
        uploadFile.transferTo(new File(path, fileName));

        //跳转页面
        return "success";
    }
}

在这里插入图片描述
5、在SpringMVC.xml中配置文件解析器

	<!--
        注意:文件上传的解析器 id 是固定的,不能起别的名称,否则无法实现请求参数的绑定。(不光是文件,其他字段也将无法绑定)
        设置上传文件的最大尺寸为 5MB,或者 value=5242880
    -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize" value="#{1024 * 1024 * 5}"></property>
    </bean>

运行结果:

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
顺着打印出来的path 我们可以找到上传图片的位置。

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值