2.5 springBoot文件上传

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_16855077/article/details/84880775

1.编写controller代码

package com.cloudtech.controller;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

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

/**
 * 文件上传
* @ClassName: UploadController  
* @Description:   
* @author wude  
* @date 2018年12月7日  
*
 */
@RestController
public class UploadController {
	@RequestMapping("fileUpload")
	public Map<String,Object> fileUpload(MultipartFile file){
		System.out.println("文件名称:"+file.getOriginalFilename());
		try {
			file.transferTo(new File("D:/test/"+file.getOriginalFilename()));
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("msg", "文件上传成功!");
		return map;
		
	}
}

@RestController注解实际上就是@controller加@responseBody的组合,返回的json格式。在类上增加这个注解,表示该类的所有方法都返回json格式

2.前端代码

<!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/>
		<button>上传图片</button>
	</form>
</body>
</html>

 注意:name为file,跟后台接收的字段名要对应,不然值无法映射成功。而不是随便取一个名字就可以的。

3. application.yml

server:
  port: 8082
  
  
spring:
  http:
    multipart:
      max-file-size: 2MB   #设置单个文件上传的大小  默认大小是10M
      max-request-size: 2MB  ##设置一次请求的总容量  

上传图片或者文件超过10M,后台会报错,因为默认的大小为10M,所以需要设置下对应的大小

4. 启动类

package com.cloudtech;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;

/**
 * springboot启动类
* @ClassName: App  
* @Description:   
* @author wude  
* @date 2018年12月6日  
*
 */
@SpringBootApplication
@ServletComponentScan  //在spring boot启动时,会扫描@webServlet,并将该类实例化
public class App2 {
	public static void main(String[] args) {
		SpringApplication.run(App2.class, args);
	}
}

5.测试

 

注意:test目录需要手动创建,因本demo只是一个简单的测试,所以,没有写对应的文件不存在就自动创建的代码。 

猜你喜欢

转载自blog.csdn.net/qq_16855077/article/details/84880775
2.5