您的位置:首页 > 编程语言 > Java开发

springBoot(10):web开发-文件上传

2017-06-18 13:42 507 查看
一、简介

Spring Boot默认使用springMVC包装好的解析器进行上传
二、代码实现
2.1、from表单

<form method="POST" enctype="multipart/form-data" action="/file/upload">
文件:<input type="file" name="roncooFile" />
<input type="submit" value="上传" />
</form>
2.2、controller

package com.example.demo.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
* 文件上传
* @Author: 我爱大金子
* @Description: 文件上传
* @Date: Created in 11:08 2017/6/18
*/
@Controller
@RequestMapping(value = "/file")
public class FileController {
private static final Logger logger = LoggerFactory.getLogger(FileController.class);
@RequestMapping(value = "/upload")
@ResponseBody
public String upload(@RequestParam("roncooFile") MultipartFile file) {
if (file.isEmpty()) {
return "文件为空";
}
// 获取文件名
String fileName = file.getOriginalFilename();
logger.info("上传的文件名为:" + fileName);
// 获取文件的后缀名
String suffixName = fileName.substring(fileName.lastIndexOf("."));
logger.info("上传的后缀名为:" + suffixName);
// 文件上传路径
String filePath = "G:/workspace/file_space/img/";
// 解决中文问题,liunx 下中文路径,图片显示问题
//fileName = UUID.randomUUID() + suffixName;
File dest = new File(filePath + fileName);
// 检测是否存在目录
if (!dest.getParentFile().exists()) {
dest.getParentFile().mkdirs();
}
try {
file.transferTo(dest);
return "上传成功";
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "上传失败";
}
}
2.3、application.properties
#默认支持文件上传
spring.http.multipart.enabled=true
#支持文件写入磁盘.
spring.http.multipart.file-size-threshold=0
#上传文件的临时目录
spring.http.multipart.location=G:/workspace/file_space/temp
# 最大支持文件大小
spring.http.multipart.max-file-size=1Mb
#最大支持请求大小
spring.http.multipart.max-request-size=10Mb
三、测试








内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  spring Boot