对于互联网项目,基本都会采用分布式的文件存储方式,比如fastdfs, 保证高用户量的时候
文件操作效率(上传,读取)。
但是对于小型产品来说,一般用户使用量不大,并且对文件的操作量也不大,甚至很小。
如果去给客户部署一套吹牛逼的分布式存储方案,无疑增大了维护成本,得不偿失。
针对上述场景,可以考虑使用base64的方式存储。代码如下:
import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiResponses; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import java.io.File; import java.io.FileInputStream; import java.util.HashMap; import java.util.Map; @RestController @RequestMapping({"/upload"}) @Api(tags="文件上传") public class UploadController { @PostMapping({"doUpload"}) @ApiOperation("文件上传(不需要token令牌)") @ApiResponses({@io.swagger.annotations.ApiResponse(code=200, message="请求成功,返回结果result:{filename 文件名},{base64 base64编码}"), @io.swagger.annotations.ApiResponse(code=400, message="请求失败")}) public Map<String, Object> doUpload(@RequestParam("file") MultipartFile file) throws Exception { if (file == null) { return new HashMap(0); } Map map = new HashMap(2); // 原文件名称 String filename = file.getOriginalFilename(); // 创建临时文件 File tempFile = File.createTempFile("tem", null); file.transferTo(tempFile); tempFile.deleteOnExit(); // 文件输入流 FileInputStream inputStream = new FileInputStream(tempFile); byte[] buffer = new byte[(int)tempFile.length()]; inputStream.read(buffer); inputStream.close(); // 转换为base64编码格式 String base64 = new sun.misc.BASE64Encoder().encode(buffer); // 上面方法中获得的base64编码中,包含有换行符,统一全部替换掉 base64 = base64.replaceAll("[\\s*\t\n\r]", ""); // 返回值 map.put("filename", filename); map.put("base64", base64); return map; } }
关于上述做几点说明:
1. 上述文件上传的时候,文件越大,产生的base64值也越大
故需要针对系统来评估数据库中对应字段的设计,存储长达,比如是 text还是longtext(做个关联表,一般不会频繁操作,优化下查询效率)
2. 返回值
返回 原文件名称和base64编码
3. 页面传值保存
尽量采用body的形式传值,因为如果是以拼接的方式,由于值太长太大,会卡死浏览器
4. 关于图片 base64方式的显示
// 把下面逗号后面的 base64编码 的文字替换成真正的base64码即可 // 然后放入到html文件中即可显示 <img src="https://img-blog.csdnimg.cn/2022010621212522899.png" alt="Springboot 文件上传(base64方式)">
下一个:MySQL碎片整理小节–实例演示