springboot整合web(二)-----------文件上传

新建springboot项目

https://blog.csdn.net/qq_43560721/article/details/104653470

项目结构

创建Controller

package cn.xxs.springbootfileupload.controller;
import java.io.File;
import java.io.IOException;


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

@RestController//当前类下的方法返回值自动做json格式的转换
public class FileUploadController {
    /**
     * 文件上传
     * @throws IOException
     * @throws IllegalStateException
     */
    @RequestMapping("/fileUpload")
    public String fileUpload(MultipartFile file) throws IllegalStateException, IOException{
        System.out.println(file.getOriginalFilename());
        file.transferTo(new File("E:/"+file.getOriginalFilename()));
        return "success";
    }
}

编写启动类

package cn.xxs.springbootfileupload;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringbootfileuploadApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootfileuploadApplication.class, args);
    }

}

在application.properties文件设置上传文件的参数及访问路径权限设置


spring.servlet.multipart.max-file-size=200MB
spring.servlet.multipart.max-request-size=200MB
spring.mvc.static-path-pattern=/static/**
spring.resources.static-locations=classpath:/static

下边两个可以不设置,只是有的版本可能不设置会出现以下404,我的是这样子的

 

设置上传页面

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="/fileUpload" method="post" enctype="multipart/form-data">
	<input type="file" name="file"/>
	<br>
	<input type="submit" value="上传">
</form>
</body>
</html>

访问项目

浏览器输入http://localhost:8080/static/upload.html

 

在这里我犯了个错误

偷懒直接如图访问

跳进了浏览器,不注意看就会往下走(注意看就会发现端口号不是8080)

会导致

发布了141 篇原创文章 · 获赞 33 · 访问量 5万+

猜你喜欢

转载自blog.csdn.net/qq_43560721/article/details/104949909