SpringBoot上传图片和IO流的基本操作,数据写入到文件中(聊天记录大数据量以文件格式存储)
浅谈
我一直都觉得上传图片好复杂,除了本地上传,还有局域网上传,公网上传乱七八糟的,不仅看不懂,还不想学,因为老是觉得本地上传没啥大用处,直到今天,我才看透,什么本地不本地的,统统都是一个套路!
在springboot2.×版本以后,上传时就不需要任何配置了,什么配置文件也不需要,啥也不讲了,上来就是干!
首先来一波IO
流的基本操作
本地创建一个文件 向里面写入内容
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
/** 在本地新建一个文件夹 里面创建一个文件 向里面写入内容 */
//1. 文件夹的路径 文件名
String directory = "E:\\test";
String filename = "test.txt";
//2. 创建文件夹对象 创建文件对象
File file = new File(directory);
//如果文件夹不存在 就创建一个空的文件夹
if (!file.exists()) {
file.mkdirs();
}
File file2 = new File(directory, filename);
//如果文件不存在 就创建一个空的文件
if (!file2.exists()) {
try {
file2.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
//3.写入数据
//创建文件字节输出流
FileOutputStream fos = new FileOutputStream(directory + "\\" + filename);
//开始写
String str = "测试数据";
byte[] bytes = str.getBytes();
//将byte数组中的所有数据全部写入
fos.write(bytes);
//关闭流
fos.close();
读取本地一个文件中的内容 写入另一个文件
import java.io.FileInputStream;
import java.io.FileOutputStream;
/** 读取本地一个文件中的内容 写入另一个文件 */
//创建文件字节输入流 这个路径下的文件必须存在
FileInputStream fis = new FileInputStream("E:\\test\\test.txt");
//创建文件字节输出流 如果这个文件不存在 会自动创建一个
FileOutputStream fos = new FileOutputStream("E:\\test\\test01.txt");
//一边读一边写
byte[] bytes = new byte[1024];
int temp = 0;
while ((temp = fis.read(bytes)) != -1) {
//将byte数组中内容直接写入
fos.write(bytes, 0, temp);
}
//刷新
fos.flush();
//关闭
fis.close();
fos.close();
1,FileWritter写入文件
FileWritter, 字符流写入字符到文件。默认情况下,它会使用新的内容取代所有现有的内容,然而,当指定一个true (布尔)值作为FileWritter构造函数的第二个参数,它会保留现有的内容,并追加新内容在文件的末尾。
示例:
String url="D:\\test.txt";
File file=new File(url);
if(!file.exists()){
file.createNewFile();
}
FileWriter fileWriter=null;
BufferedWriter bufferedWriter=null;
try {
fileWriter=new FileWriter(file,true);
bufferedWriter=new BufferedWriter(fileWriter);
bufferedWriter.write(list.toString());
} catch (IOException e) {
e.printStackTrace();
}finally {
bufferedWriter.close();
osBufferedWriter.close();
}
2,FileOutputStream写入文件
文件输出流是一种用于处理原始二进制数据的字节流类。为了将数据写入到文件中,必须将数据转换为字节,并保存到文件。请参阅下面的完整的例子。
File file = new File("c:/newfile.txt");
String content = "This is the text content";
try (FileOutputStream fop = new FileOutputStream(file)) {
if (!file.exists()) {
file.createNewFile();
}
byte[] contentInBytes = content.getBytes();
fop.write(contentInBytes);
fop.flush();
fop.close();
} catch (IOException e) {
e.printStackTrace();
}
下面是我自己做个一个商城项目上传图片的demo
首先是数据库表
这个项目使用的是springboot,mybatis,thymeleaf
前台html页面代码
<div id="div">
<form action="/demo/upload" method="post" enctype="multipart/form-data">
上架的商品名称:<input class="input" type="text" name="name"><br>
商品尺寸:<select class="input" name="size">
<option value="M">M</option>
<option value="L">L</option>
<option value="XL">XL</option>
<option value="XXL">XXL</option>
</select><br>
商品价格:<input class="input" type="text" name="price"><br>
上架商品数量:<input class="input" type="text" name="number"><br>
商品颜色:<select class="input" name="color">
<option value="蓝色">蓝色</option>
<option value="白色">白色</option>
<option value="黑色">黑色</option>
<option value="灰色">灰色</option>
</select><br>
商品类型:<select class="input" name="kind">
<option value="男装">男装</option>
<option value="女装">女装</option>
<option value="童装">童装</option>
<option value="时尚包包">时尚包包</option>
</select><br>
原价:<input class="input" type="text" name="preprice"><br>
商品图片:<input class="input" type="file" name="pic"><br>
上架日期:<input class="input" type="date" name="time"><br>
<input type="submit" value="确认上架">
</form>
</div>
controller层代码
/**
* 商品图片上传
*/
@RequestMapping("/upload")
public String upload(@RequestParam(value = "pic") MultipartFile pic,@RequestParam Map param,Model model) throws ParseException {
System.err.println("传过来的值"+param);
if(pic.isEmpty()){
System.err.println("上传文件不可为空");
}
String fileName=pic.getOriginalFilename();//得到文件名
String suffixName=fileName.substring(fileName.lastIndexOf("."));//得到后缀名
System.err.println("suffixName:"+suffixName);
String filepath="D:/tempFiles/files/";//指定图片上传到哪个文件夹的路径
fileName= UUID.randomUUID()+suffixName;//重新命名图片,变成随机的名字
System.err.println("fileName:"+fileName);
File dest=new File(filepath+fileName);//在上传的文件夹处创建文件
try {
pic.transferTo(dest);//把上传的图片写入磁盘中
} catch (IOException e) {
e.printStackTrace();
}
//到这里为止,下面的都不用再看了,跟上传没关系,都是实体类传值竟然麻烦成这个样子
Shangpin shangpin=new Shangpin();
//这里就不想改了,把fileName当成picpath传过去算了
String picpath=fileName;
shangpin.setPicpath(picpath);
shangpin.setName((String) param.get("name"));
shangpin.setSize((String) param.get("size"));
double price=Double.parseDouble(param.get("price").toString());
shangpin.setPrice(price);
shangpin.setNumber(Integer.valueOf(param.get("number").toString()));
shangpin.setColor((String) param.get("color"));
double preprice=Double.parseDouble(param.get("preprice").toString());
shangpin.setPreprice(preprice);
shangpin.setKind((String) param.get("kind"));
String sellerAccount=phone;
shangpin.setSellerAccount(sellerAccount);
SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd");
shangpin.setTime(simpleDateFormat.parse((String) param.get("time")));
int i=selectService.insertSP(shangpin);
if(i>0){
model.addAttribute("info","商品上传成功!");
return "forward:getSP";
}
model.addAttribute("info","商品上传失败!");
return "forward:getSP";
}
对了,千万不能忘记实体类,就和上边那张表的字段相对应,一个也不能错,错了它也会错。
package com.qianlong.entity;
import java.util.Date;
public class Shangpin {
private Integer id;
private String name;
private String size;
private double price;
private String sellerAccount;
private int number;
private String color;
private double preprice;
private String picpath;
private Date time;
private String kind;
//set和get方法省略
service层忽略,来看dao层,也就是mapper文件
/**
* 上架商品(上传商品图片)
*/
@Insert(value = "insert into shangpin(name,size,price,sellerAccount,number,color," +
"preprice,picpath,time,kind) values(#{name},#{size},#{price}," +
"#{sellerAccount},#{number},#{color},#{preprice},#{picpath},#{time},#{kind})")
int insertSP(Shangpin shangpin);
然后就完成上传了,上传成功之后跳转到列表页面,使用thymeleaf提示上传成功
<!DOCTYPE html>
<html xmlns:th="www.thymeleaf.org">
<head>
<meta charset="utf-8" />
<title>商品管理</title>
<script th:src="@{/js/jquery.1.12.4.min.js}" charset="UTF-8"></script>
</head>
<body>
<a style="margin-left: 440px" href="/demo/backAddSP">商品上架</a><span style="color: red;" th:text="${info}"></span>
<table border="4">
<thead>
<tr>
<th width="100px">序号</th>
<th width="100px">商品名称</th>
<th width="100px">尺寸</th>
<th width="100px">价格</th>
<th width="100px">数量</th>
<th width="100px">颜色</th>
<th width="100px">原价</th>
<th width="100px">商品类型</th>
<th width="100px">图片路径</th>
<th width="100px">添加时间</th>
<th width="100px">操作</th>
</tr>
</thead>
<tbody>
<!-- 遍历集合,如果被遍历的变量 userList 为 null 或者不存在,则不会进行遍历,也不报错-->
<tr th:each="user : ${list}">
<!-- 将用户的主键 uId 存在在 name 属性中-->
<td width="100px" th:text="${user.id}"></td>
<td width="100px" th:text="${user.name}"></td>
<td width="100px" th:text="${user.size}"></td>
<td width="100px" th:text="${user.price}"></td>
<td width="100px" th:text="${user.number}"></td>
<td width="100px" th:text="${user.color}"></td>
<td width="100px" th:text="${user.preprice}"></td>
<td width="100px" th:text="${user.kind}"></td>
<td width="100px" th:text="${user.picpath}"></td>
<!-- 使用dates对象格式化日期-->
<td width="100px" th:text="${#dates.format(user.time, 'yyyy-MM-dd')}"></td>
<td style="text-align: center" width="100px"><intput type="button" th:onclick="del([[${user.id}]]);">删除</intput></td>
</tr>
</tbody>
</table>
<script>
function del(id) {
alert(id);
}
</script>
</body>
</html>
图片上传到这里就结束啦,有问题欢迎留言!
项目地址:链接:https://pan.baidu.com/s/1DRr1Y9h0T7nvOfEL0oGvyw 提取码:w6dt
-------------------------------------------
个性签名:独学而无友,则孤陋而寡闻。做一个灵魂有趣的人!
如果觉得这篇文章对你有小小的帮助的话,记得在右下角点个“推荐”哦,博主在此感谢!
万水千山总是情,打赏一分行不行,所以如果你心情还比较高兴,也是可以扫码打赏博主,哈哈哈(っ•̀ω•́)っ✎⁾⁾!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)