1.利用开源图片服务器 zimg搭建属于自己的服务器:
1.zimg 官网地址(http://zimg.buaa.us/)
2.下载:
git clone https://github.com/buaazp/zimg -b master --depth=1
cd zimg
make 具体步骤参考这个地址(http://zimg.buaa.us/downloads/)
3.启动图片服务器地址:
zimg解压路径下:/usr/local/zimg
.使用:./zimg conf/zimg.lua
zimg.lua
4。打开图片服务器web页面:(http://IP:4869/)
2.用程序实现:spingboot实现:
@RequestMapping(value = "/upload", method = RequestMethod.POST)
@ResponseBody
public String upload(@RequestParam("file") MultipartFile file) {
if (file.isEmpty()) {
return "上传失败,请选择文件";
}
String upload_url = "http://IP:4869/upload";
System.out.println("---ext--" + file.getName());
System.out.println("---ext--" + file.getOriginalFilename());
String filename=file.getOriginalFilename();
String prefix=filename.substring(filename.lastIndexOf(".")+1);
System.out.println("文件后缀:"+prefix);
try {
System.out.println("上传图片服务器:" + sendPost(upload_url, file.getBytes(), prefix));
} catch (IOException e) {
e.printStackTrace();
}
try {
return sendPost(upload_url, file.getBytes(), prefix);
} catch (IOException e) {
e.printStackTrace();
}
return "失败";
}
private static byte[] imageBinary(String file_path, String fileType) {
File f = new File(file_path);
BufferedImage bi;
try {
bi = ImageIO.read(f);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ImageIO.write(bi, fileType, bos);
return bos.toByteArray();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
// 向指定 URL 发送POST方法的请求
private static String sendPost(String url, byte[] PostData, String fileType) {
OutputStream outStream = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(url);
// 打开和URL之间的连接
URLConnection conn = realUrl.openConnection();
// 设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("Content-Type", fileType);
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
//二进制
outStream = conn.getOutputStream();
outStream.write(PostData);
outStream.flush();
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("发送 POST 请求出现异常!" + e);
e.printStackTrace();
}
//使用finally块来关闭输出流、输入流
finally {
try {
if (outStream != null) {
outStream.close();
}
if (in != null) {
in.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return result;
}