Spring MVC文件上传!!!

注意:我使用的是tomcat插件,不需要配置tomcat了

Spring MVC文件上传!!!_第1张图片

添加依赖:

 war

    
        
            org.springframework
            spring-context
            5.1.8.RELEASE
        
        
            org.springframework
            spring-web
            5.1.8.RELEASE
        
        
            org.springframework
            spring-webmvc
            5.1.8.RELEASE
        
        
        
            com.fasterxml.jackson.core
            jackson-databind
            2.9.0
        
        
            javax.servlet
            servlet-api
            2.5
            provided
        

        
            javax.servlet.jsp
            jsp-api
            2.0
            provided
        
        
        
            commons-fileupload
            commons-fileupload
            1.3.1
        
    
    
        
            
            
                org.apache.tomcat.maven
                tomcat7-maven-plugin
                2.2
                
                    
                    8080
                    
                    /
                
            
        
    

配置文件上传解析器:springmvc.xml



    
    

    
    
        
        
    

    
    


    
    
        
        
    

 配置web.xml:



    
    
    
        springmvc
        org.springframework.web.servlet.DispatcherServlet
        
            contextConfigLocation
            classpath:springmvc.xml
        
        1
    
    
        springmvc
        /
    

 编写controller:

/*
 * Copyright (c) 2020, 2024,  All rights reserved.
 *
 */
package com.by.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;

/**
 * 

Project: SpringMVC - uploadController

*

Powered by scl On 2024-01-10 11:02:34

*

描述:

* * @author 孙臣龙 [[email protected]] * @version 1.0 * @since 17 */ @Controller @RequestMapping("/account") public class uploadController { @PostMapping("/upload") public String upload(MultipartFile img, HttpServletRequest request, Model model) throws IOException { //获取上传目录 String realPath = request.getSession().getServletContext().getRealPath("uploads"); //判断目录是否存在 File file = new File(realPath); if (!file.exists()){ file.mkdirs(); } //上传 String filename = img.getOriginalFilename(); img.transferTo(new File(realPath,filename)); model.addAttribute("msg",filename); return "success"; } }

在index.jsp里面定义超链接 :

文件:

 上传成功跳转页面:success.jsp

结果展示:

Spring MVC文件上传!!!_第2张图片

 Spring MVC文件上传!!!_第3张图片

你可能感兴趣的:(spring,mvc,java,intellij-idea,tomcat,maven,log4j)