基础版本的文件读取操作:将文件内容读取并以blob格式保存至数据库
//新增房间
@RequestMapping(value = "/admin/room/add")
@ResponseBody
public Message addHotel(@RequestParam(value = "photos", required = false) MultipartFile file) throws IOException {hotelInfo hotelinfo = new hotelInfo();
//文件读取操作
if (file.isEmpty()) {
return Message.createErr("照片无内容");
}
CommonsMultipartFile cFile = (CommonsMultipartFile) file;
DiskFileItem fileItem = (DiskFileItem) cFile.getFileItem();
InputStream inputStream = fileItem.getInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int len = 1024;
byte tmp [] = new byte[len];
int i ;
while((i=inputStream.read(tmp, 0, len))>0){
baos.write(tmp, 0, i);
}
byte imgs[] = baos.toByteArray();
hotelinfo.setImageUrl(imgs);
return Message.createSuc(hotelService.insert(hotelinfo));}
上传图片:前端传递图片,后端调用图床接口返回url保存至数据库
参考网址:JAVA如何调用API
public static HttpEntity upload() {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost("https://sm.ms/api/upload");//建立HttpPost对象,改成自己的地址
//URL resource = upload.class.getClassLoader().getResource("screenshot.png");
//String path = resource.getPath();
//System.out.println("path = " + path);
File file = new File("D:\\Users\\lu\\Desktop\\images\\1.jpg");//相对路径使用不了的话,使用图片绝对路径
if(!file.exists()){//判断文件是否存在
System.out.print("文件不存在");
return null;
}
FileBody bin = new FileBody(file, ContentType.create("image/jpg", Consts.UTF_8));//创建图片提交主体信息
HttpEntity entity = MultipartEntityBuilder
.create()
.setCharset(Charset.forName("utf-8"))
.setContentType(ContentType.MULTIPART_FORM_DATA)
.addPart("smfile", bin)//添加到请求
.build();
httpPost.setEntity(entity);
httpPost.addHeader("user-agent","Mozilla/4.0 (compatible;MSIE 6.0;Windows NT 5.1;SV1)");
httpPost.addHeader("connection", "Keep-Alive");
HttpResponse response= null;//发送Post,并返回一个HttpResponse对象
try {
response = httpClient.execute(httpPost);
if(response.getStatusLine().getStatusCode()==200) {//如果状态码为200,就是正常返回
String result = EntityUtils.toString(response.getEntity());
//System.out.print(result);
}
//System.out.println("response = " + response);
} catch (IOException e) {
e.printStackTrace();
}
//System.out.print(response);
//System.out.print("结束");
return response.getEntity();
}
还参考了很多代码,一时找不到了,有机会补充。