My personal blog system featured image upload function is to use file upload component layui do.
Another use of an ecosystem framework, are unified as far as possible with the corresponding frame of ecological solutions, because this way, there are several benefits?
1. unity without hybridity, facilitate the development of appropriate coding standard, easy maintenance;
2. high reusability;
3. developers will not leave the company which led not find people to do this thing;
On these three points, enough for enterprises to reduce costs associated with development
Front-end code to achieve:
<!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>Upload install package or update package </ Button> <Script the src = " ../layui/layui.js " > </ Script> <Script> layui.use ( ' Upload ' , function () { var Upload = layui.upload ; // executing instances var uploadInst = upload.render ({ elem: ' #uploadExample ' // binding element , URL: ' HTTP: // localhost: 8090 / Web-Blog / User / the uploadFile ' // upload interfaces , accept : ' File ' , DONE: function (RES) { layui.use('Layer ' , function () { var Layer = layui.layer; layer.msg (res.url, { Time: 6000 , // after 6s off automatically icon: . 1 }); }); } , error: function () { // request exception callback } }); }); </ Script> </ body> </ HTML>
Back-end code (I used here is Tencent cloud object storage):
2 . 3 . 4 . 5 . 6 . 7 . 8 . 9 10 . 11 12 is 13 is 14 15 16 . 17 18 is . 19 20 is 21 is 22 is 23 is 24 25 26 is 27 28 29 30 31 is 32 33 is 34 is 35 36 37 [ 38 is 39 @PostMapping (value = " / the uploadFile " ) @ApiOperation ( " upload " ) 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); // Get File Path String fileURL = cosClientUtil.getFileUrl (name); logger.info ( " fileURL = " + fileURL); // file processing path 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; }
Universal Tencent cloud object storage tools:
Tencent cloud object storage do not understand, you can refer to the official document:
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; java.util.Date Import; Import java.util.Random; public class COSClientUtil { Private COSClient cOSClient; Private static Final ENDPOINT String = " ENDPOINT " ; // user can specify the domain name, the domain name is not specified or the default generated // SecretID Private static Final String = the SecretID " the SecretID " ; // secretKey Private static Final secretKey String = " secretKey " ; // bucket name Private staticString bucketName = Final " bucketName " ; // public private read write // APPID Private static Final APPID String = " APPID " ; // 1 initialization user identity information (the SecretID, secretKey) Private static COSCredentials cred = new new BasicCOSCredentials (the SecretID, secretKey ); // region 2 provided the bucket, COS local referred Referring https://cloud.tencent.com/document/product/436/6224 Private static the ClientConfig ClientConfig = new new the ClientConfig ( new 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); } the catch (IOException E) { e.printStackTrace (); } the finally { the try { IF (inStream =! null ) { instream.close (); } } the catch (IOException E) { e.printStackTrace ( ); } cosclient.shutdown (); } return RET; } / * * * get the file path to obtain pre-signature links used before uploading files. * * @Param file specified by fileurl @Return * * / public String getFileUrl (String fileURL) { return getUrl (fileURL) .toString (); } / * * * signatures upload link generating pre * * @param Key * @return * / public the URL getUrl (String Key) { // set URL expiration time of 10 * 24 * 1000 * 3600L * 10 365 a Date expiration = new new a Date (System.currentTimeMillis () + 3600L * 1000 * 24 * 365 * 10 ); // generated URL URL URL =cOSClient.generatePresignedUrl (bucketName, Key, expiration, HttpMethodName.PUT); return URL; } / * * * the Description: Analyzing Cos service file uploaded file contentType * * @param filenameExtension file extension * @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()); } }