今天我们需要做一个文件上传,为我们后边要做的webscoket即时聊天做准备。
一:在配置文件中配置文件上传参数
spring:
profiles:
# 对,你没看错,环境对应的名称就是子环境-后边的名字,我这里分别对应 dev|product
active: dev
# 上传文件配置
http:
multipart:
enabled: true # 默认支持文件上传
file-size-threshold: 0 # 支持文件写入磁盘
max-file-size: 50MB # 最大文件上传大小
max-request-size: 100MB # 最大支持请求大小
upload-url: https://resource.guanchao.site/im/
---
# 生产环境
spring:
profiles: product
upload-path: /usr/share/nginx/html/resource/im/
---
---
# 测试环境
spring:
profiles: dev
upload-path: E:\camellia\doc\Java\
---
以上的配置是配置在项目的yml配置文件中。我分别配置了测试环境和生产环境的不同变量。
二:上传文件代码
package com.springbootblog.service.serviceImpl.fontend;
import com.springbootblog.service.fontend.ImUploadService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
@Service
public class ImUploadServiceImpl implements ImUploadService
{
/**
* 上传文件存放目录
*/
@Value("${spring.upload-path}")
private String basePath;
/**
* 图片url
*/
@Value("${spring.upload-url}")
private String uploadUrl;
@Override
public Map<String, Object> uploadImage(@RequestParam("file") MultipartFile file, HttpServletRequest request)
{
if (file != null && !file.isEmpty())
{
HttpSession session = request.getSession();
System.out.println(session);
Integer userid = (Integer)session.getAttribute("userid");
System.out.println(userid);
if(userid == null)
{
userid = 0;
}
System.out.println(userid);
// =====================================================================
// 文件上传逻辑
// 获取文件名
String fileName = file.getOriginalFilename();
// 获取文件内容类型
String contentType = file.getContentType();
// 获取文件大小
long fileSize = file.getSize();
//声明一个指定目录,用来存放上传的文件
String realPath = basePath + userid + "/";
// 创建目录
File dir = new File(realPath);
if(!dir.exists())
{
dir.mkdirs();
System.out.println("目录创建中!");
}
System.out.println("目录创建之后");
// 重命名文件 每个上传的文件名不重复UUID, 当前时间的毫秒数
String suffix = fileName.substring(fileName.lastIndexOf(".")); //1.jpg .jpg
// 新的文件名
fileName = UUID.randomUUID()+suffix;
System.out.println(fileName);
try
{
System.out.println("上传文件");
file.transferTo(new File(dir,fileName));
}
catch (IOException e)
{
e.printStackTrace();
}
Map<String,Object> array = new HashMap<>(3);
array.put("url", uploadUrl + userid + "/" +fileName);
array.put("alt", "");
array.put("href", "");
Map<String,Object> result = new HashMap<>(2);
result.put("errno",0);
result.put("data",array);
return result;
}
else
{
// 文件为空处理逻辑
Map<String,Object> result = new HashMap<>(2);
result.put("code",-1);
result.put("msg","文件流为空!");
return result;
}
}
}
上传这部分就比较简单了,重要的代码部分上边都有注释。参照即可。
这里需要注意一下,上传的请求方式必须是POST,上传的文件名字和方法接收的参数名字必须相同,否则是接收不到上传的文件流的。
以上大概就是SpringBoot框架中文件上传的简单应用。
有好的建议,请在下方输入你的评论。