【Springmvc】实现文件上传

一、项目路径

 二、代码部分

1、RestFulController.java

package com.qingruan.servlet;

import com.qingruan.bean.UserInfo;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/restful")
public class RestFulController {

    //MultipartFile类型即为接收上传的文件,参数的名称与input中的name属性的名称一致
    @PostMapping("/upload")
    public String getFile(MultipartFile file, HttpServletRequest request) throws Exception{
        //获得文件存储路径(绝对路径)
        String path = request.getServletContext().getRealPath("/upload");
        //获取原文件名
        String filename = file.getOriginalFilename();
        //创建文件实例
        File filePath = new File(path,filename);
        //如果文件目录不存在,创建目录
        if (!filePath.getParentFile().exists()){
            filePath.getParentFile().mkdirs();
            System.out.println("创建目录:"+filePath);
        }
        //写入文件
        file.transferTo(filePath);
        return file.getOriginalFilename();
    }


}

2、spring-mvc.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
  

猜你喜欢

转载自blog.csdn.net/xjj1128/article/details/128203441