SpringBoot- 文件上传

 


# 更改文件上传大小
spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=10MB


# 指定静态资源位置  可以url访问
spring.web.resources.static-locations=/upload/

 

package com.example.demo.controller;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

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


@RestController
public class FileController {


    @PostMapping("/upload")
    public String upload(String name, MultipartFile photo, HttpServletRequest request) throws IOException {

        System.out.println(name);
        System.out.println(photo.getName());
        System.out.println(photo.getContentType());
        System.out.println(photo.getOriginalFilename());

        String servletPath = request.getServletPath();
        System.out.println(servletPath);
        String realPath = request.getServletContext().getRealPath("/upload/");
        System.out.println(realPath);
        saveFile(photo,realPath);
        return "上传了"+name;

    }

    public void saveFile(MultipartFile photo,String path) throws IOException {

        File dir = new File(path);
        if (!dir.exists()){
            dir.mkdir();
        }

        File file = new File(path + photo.getOriginalFilename());
        photo.transferTo(file);

    }


}

 

posted @ 2024-02-05 10:24  钟鼎山林  阅读(35)  评论(0编辑  收藏  举报