您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
一、简介
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
三、测试



免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。