我個人博客系統上傳特色圖片功能就是用layui上傳文件組件做的。
另外采用某個生態框架,盡量都統一用該生態框架對應的解決方案,因為這樣一來,有這么幾個好處?
1.統一而不雜糅,有利於制定相應的編碼規范,方便維護;
2.復用性高;
3.不會因公司開發人員的離職而導致一時找不到人來做這件事情;
就這三點,也足以讓企業降低相應的開發成本
前端代碼實現:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>upload</title> <link rel="stylesheet" href="../layui/css/layui.css" media="all"> </head> <body> <button type="button" class="layui-btn" id="uploadExample"> <i class="layui-icon"></i>上傳安裝包或更新包 </button> <script src="../layui/layui.js"></script> <script> layui.use('upload', function(){ var upload = layui.upload; //執行實例 var uploadInst = upload.render({ elem: '#uploadExample' //綁定元素 ,url: 'http://localhost:8090/blog-web/user/uploadFile' //上傳接口 ,accept: 'file' ,done: function(res){ layui.use('layer', function(){ var layer = layui.layer; layer.msg(res.url, { time: 6000, //6s后自動關閉 icon:1 }); }); } ,error: function(){ //請求異常回調 } }); }); </script> </body> </html>
后端代碼(我在這里采用的是騰訊雲對象存儲):
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 @PostMapping(value = "/uploadFile") @ApiOperation("上傳文件") public JSONObject uploadFile(HttpServletRequest request) throws IOException { JSONObject json = new JSONObject(); try { COSClientUtil cosClientUtil = new COSClientUtil(); MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; // 獲取上傳的文件 MultipartFile multiFile = multipartRequest.getFile("file"); String name = cosClientUtil.uploadFileCos(multiFile); // 文件名稱 logger.info("name = " + name); // 獲取文件路徑 String fileUrl = cosClientUtil.getFileUrl(name); logger.info("fileUrl = " + fileUrl); // 對文件路徑進行處理 String dbFileUrl = fileUrl.substring(0, fileUrl.indexOf("?")); logger.info("dbFileUrl = " + dbFileUrl); json.put("url", dbFileUrl); json.put(CommonEnum.RETURN_CODE, "000000"); json.put(CommonEnum.RETURN_MSG, "success"); } catch (Exception e) { e.printStackTrace(); json.put(CommonEnum.RETURN_CODE, "333333"); json.put(CommonEnum.RETURN_MSG, "特殊異常"); } return json; }
通用騰訊雲對象存儲工具類:
對於騰訊雲對象存儲不明白的,可以參考官方文檔:
https://cloud.tencent.com/document/product/436/6474
import com.qcloud.cos.COSClient; import com.qcloud.cos.ClientConfig; import com.qcloud.cos.auth.BasicCOSCredentials; import com.qcloud.cos.auth.COSCredentials; import com.qcloud.cos.http.HttpMethodName; import com.qcloud.cos.model.GetObjectRequest; import com.qcloud.cos.model.ObjectMetadata; import com.qcloud.cos.model.PutObjectRequest; import com.qcloud.cos.model.PutObjectResult; import com.qcloud.cos.region.Region; import org.apache.http.ProtocolException; import org.springframework.web.multipart.MultipartFile; import java.io.*; import java.net.HttpURLConnection; import java.net.URL; import java.util.Date; import java.util.Random; public class COSClientUtil { private COSClient cOSClient; private static final String ENDPOINT = "ENDPOINT"; //用戶可以指定域名,不指定則為默認生成的域名 //secretId private static final String secretId = "secretId"; //secretKey private static final String secretKey = "secretKey"; //存儲桶名稱 private static final String bucketName = "bucketName";//公有讀私有寫 //APPID private static final String APPID = "APPID"; // 1 初始化用戶身份信息(secretId, secretKey) private static COSCredentials cred = new BasicCOSCredentials(secretId, secretKey); // 2 設置bucket的區域, COS地域的簡稱請參照 https://cloud.tencent.com/document/product/436/6224 private static ClientConfig clientConfig = new ClientConfig(new Region("ap-beijing-1")); // 3 生成cos客戶端 private static COSClient cosclient = new COSClient(cred, clientConfig); public COSClientUtil() { cOSClient = new COSClient(cred, clientConfig); } public static String getSecretId() { return secretId; } public static String getsecretKey() { return secretKey; } public static String getBucketName() { return bucketName; } public static String getAPPID() { return APPID; } /** * 銷毀 */ public void destory() { cOSClient.shutdown(); } /** * 上傳文件 * @param file * @return */ public String uploadFileCos(MultipartFile file) { String originalFilename = file.getOriginalFilename(); try { InputStream inputStream = file.getInputStream(); this.uploadFileCos(inputStream, originalFilename); } catch (Exception e) { e.printStackTrace(); } return originalFilename; } /** * 上傳文件 * @param instream * @param fileName * @return */ public String uploadFileCos(InputStream instream, String fileName) { String ret = ""; try { // 創建上傳Object的Metadata ObjectMetadata objectMetadata = new ObjectMetadata(); objectMetadata.setContentLength(instream.available()); objectMetadata.setCacheControl("no-cache"); objectMetadata.setHeader("Pragma", "no-cache"); objectMetadata.setContentType(getcontentType(fileName.substring(fileName.lastIndexOf(".")))); objectMetadata.setContentDisposition("inline;filename=" + fileName); PutObjectResult putResult = cOSClient.putObject(bucketName,fileName, instream, objectMetadata); ret = putResult.getETag(); System.out.println(ret); } catch (IOException e) { e.printStackTrace(); } finally { try { if (instream != null) { instream.close(); } } catch (IOException e) { e.printStackTrace(); } cosclient.shutdown(); } return ret; } /** * 獲得文件路徑 在上傳文件之前獲取預簽名鏈接用的。 * * @param fileUrl * @return */ public String getFileUrl(String fileUrl) { return getUrl(fileUrl).toString(); } /** * 生成預簽名的上傳鏈接 * * @param key * @return */ public URL getUrl(String key) { // 設置URL過期時間為10年 3600l* 1000*24*365*10 Date expiration = new Date(System.currentTimeMillis() + 3600L * 1000 * 24 * 365 * 10); // 生成URL URL url = cOSClient.generatePresignedUrl(bucketName, key, expiration, HttpMethodName.PUT); return url; } /** * Description: 判斷Cos服務文件上傳時文件的contentType * * @param filenameExtension 文件后綴 * @return String */ public static String getcontentType(String filenameExtension) { if (filenameExtension.equalsIgnoreCase("bmp")) { return "image/bmp"; } if (filenameExtension.equalsIgnoreCase("gif")) { return "image/gif"; } if (filenameExtension.equalsIgnoreCase("jpeg") || filenameExtension.equalsIgnoreCase("jpg") || filenameExtension.equalsIgnoreCase("png")) { return "image/jpeg"; } if (filenameExtension.equalsIgnoreCase("html")) { return "text/html"; } if (filenameExtension.equalsIgnoreCase("txt")) { return "text/plain"; } if (filenameExtension.equalsIgnoreCase("vsd")) { return "application/vnd.visio"; } if (filenameExtension.equalsIgnoreCase("pptx") || filenameExtension.equalsIgnoreCase("ppt")) { return "application/vnd.ms-powerpoint"; } if (filenameExtension.equalsIgnoreCase("docx") || filenameExtension.equalsIgnoreCase("doc")) { return "application/msword"; } if (filenameExtension.equalsIgnoreCase("xml")) { return "text/xml"; } return "image/jpeg"; } /** * 下載文件 * @param downFile * @param key * @param bucketName */ public void download(File downFile, String key, String bucketName) { GetObjectRequest getObjectRequest = new GetObjectRequest(bucketName, key); ObjectMetadata downObjectMeta = cOSClient.getObject(getObjectRequest, downFile); System.out.println(downObjectMeta.getContentLength()); } }