一、什么是图片服务器
图片服务器是专门为图片读写操作优化的独立服务器,在当今项目的使用中,图片等静态资源成为不可或缺的载体,那么当我们访问量逐渐增大时,访问速度日趋下降时,我们此时就应该考虑从项目中抽取一部分功能。通常,如果网站存在大量图片读写操作,那么应该首先把图片服务分离出来,也就是建立独立的图片服务器。确保在访问的时候不会因为图片问题而奔溃,并且更加方便做扩容、容灾和数据迁移。
二、图片服务器的优势1、分担 Web 服务器的 I/O 负载 - 将耗费资源的图片服务分离出来,提高服务器的性能和稳定性 2、能够专门对图片服务器进行优化 - 为图片服务设置有针对性的缓存方案,减少带宽成本,提高访问速度 3、提高网站的可扩展性 - 通过增加图片服务器,提高图片吞吐能力
本篇文章主要简单实用MutiPartFile进行上传文件。 可以直接粘贴使用。
/**
* bbyte:图片的字节流
* type:需要保存的文件类型。
*/
public static Map UpIOFile(byte[] bbyte,String type){
//获取oss的url
String uploadUrl =URLConfig.getOSSFileURL();
String end = "\r\n";
String twoHyphens = "--";
String boundary = "------------------952765431";
try {
URL url = new URL(uploadUrl);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
httpURLConnection.setUseCaches(false);
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
httpURLConnection.setRequestProperty("Charset", "UTF-8");
httpURLConnection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
DataOutputStream dos = new DataOutputStream(httpURLConnection.getOutputStream());
dos.writeBytes(twoHyphens + boundary + end);
dos.writeBytes("Content-Disposition: form-data; name=\"file\"; filename=\"test."+type+"\"" + end);
dos.writeBytes(end);
dos.write(bbyte);
dos.writeBytes(end);
dos.writeBytes(twoHyphens + boundary + twoHyphens + end);
dos.flush();
// 读取服务器返回结果
InputStream is = httpURLConnection.getInputStream();
InputStreamReader isr = new InputStreamReader(is, "utf-8");
BufferedReader br = new BufferedReader(isr);
String result = br.readLine();
is.close();
Map resultMap = JsonUtil.jsonString2Map(result);
return resultMap;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
使用实例:
Map resMap = MutiPartFileUtil.UpIOFile(bbyte,"pdf");
因为文件服务器是现成的,所以这里没有介绍文件服务器的搭建,有时间会补上。