其他分享
首页 > 其他分享> > springMVC文件上传

springMVC文件上传

作者:互联网

文件上传

单文件上传

upload.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@page isELIgnored="false" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<form action="/upload" method="post" enctype="multipart/form-data">
    file: <input type="file" name="img"><br>
    <input type="submit" value="提交">
</form>
    <img src="${path}">
</body>
</html>

后端

	@RequestMapping("/upload")
    public String upload(MultipartFile img, HttpServletRequest request) {
        String filePath = request.getServletContext().getRealPath("file");
        File mkdir = new File(filePath);
        if(!mkdir.exists()) // 这是为了创建文件夹
            mkdir.mkdir();
        String filename = img.getOriginalFilename();
        File file = new File(filePath,filename);
        try {
            img.transferTo(file);
            // request.setAttribute("path","/file/"+filename); 存下图片的访问路径
            request.setAttribute("path","/file/"+filename);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "upload";
    }

选取文件提交后
在这里插入图片描述

注意事项
得导入对应的jar包

	<!-- 文件上传组件 -->
	<dependency>
      <groupId>commons-io</groupId>
      <artifactId>commons-io</artifactId>
      <version>2.8.0</version>
    </dependency>

    <dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.3.3</version>
    </dependency>

    <!-- servlet-api -->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.1.0</version>
      <scope>provided</scope>
    </dependency>

  <!-- jstl -->
    <dependency>
      <groupId>jstl</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>

标签:文件,springMVC,request,mkdir,commons,filename,upload,file,上传
来源: https://blog.csdn.net/qq_40036427/article/details/122340381