옮겨 싣다https://www.cnblogs.com/baizhanshi/p/5593431.html
아리운 OSS에 사진을 올리고 사진을 올리는 외부 URL을 얻으려면
아무 말도 안 하고 코드로 바로 올라가.
1.html:
1 2 3 4 "/bcis/api/headImgUpload.json" method= "post" enctype= "multipart/form-data" > "file" name= "file" > "submit" value= " " >
2.controller:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 @RequestMapping (value = "/headImgUpload.json" , method = RequestMethod.POST) @ResponseBody public Map headImgUpload(HttpServletRequest request,MultipartFile file) { Map value = new HashMap(); value.put( "success" , true ); value.put( "errorCode" , 0 ); value.put( "errorMsg" , "" ); try { String head = userService.updateHead(file, 4 ); // ,4 userId 。 value.put( "data" , head); } catch (IOException e) { e.printStackTrace(); value.put( "success" , false ); value.put( "errorCode" , 200 ); value.put( "errorMsg" , " " ); } return value; }
3. 서비스@Autowired
private OSSClientUtil ossClient;
1 2 3 4 5 6 7 8 9 10 @Override public String updateHead(MultipartFile file, long userId) throws IOException{ if (file == null || file.getSize() <= 0 ) { throw new ImgException( " " ); } String name = ossClient.uploadImg2Oss(file); String imgUrl = ossClient.getImgUrl(name); userDao.updateHead(userId, imgUrl); // return imgUrl; }
4. 업로드된 아리운의 도움말 클래스 OSSClientUtil
1 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 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 import java.io.*; import java.net.URL; import java.util.Date; import java.util.Random; import com.fndsoft.bcis.exception.ImgException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.aliyun.oss.OSSClient; import com.aliyun.oss.model.ObjectMetadata; import com.aliyun.oss.model.PutObjectResult; import org.springframework.util.StringUtils; import org.springframework.web.multipart.MultipartFile; /** * OSS * * @author YuanDuDu */ public class OSSClientUtil { Log log = LogFactory.getLog(OSSClientUtil. class ); // endpoint , region private String endpoint = " endpoint" ; // accessKey private String accessKeyId = " accessKeyId" ; private String accessKeySecret = " accessKeySecret" ; // private String bucketName = "bcis" ; // private String filedir = "data/" ; private OSSClient ossClient; public OSSClientUtil() { ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret); } /** * */ public void init() { ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret); } /** * */ public void destory() { ossClient.shutdown(); } /** * * * @param url */ public void uploadImg2Oss(String url) { File fileOnServer = new File(url); FileInputStream fin; try { fin = new FileInputStream(fileOnServer); String[] split = url.split( "/" ); this .uploadFile2OSS(fin, split[split.length - 1 ]); } catch (FileNotFoundException e) { throw new ImgException( " " ); } } public String uploadImg2Oss(MultipartFile file) { if (file.getSize() > 1024 * 1024 ) { throw new ImgException( " 1M!" ); } String originalFilename = file.getOriginalFilename(); String substring = originalFilename.substring(originalFilename.lastIndexOf( "." )).toLowerCase(); Random random = new Random(); String name = random.nextInt( 10000 ) + System.currentTimeMillis() + substring; try { InputStream inputStream = file.getInputStream(); this .uploadFile2OSS(inputStream, name); return name; } catch (Exception e) { throw new ImgException( " " ); } } /** * * * @param fileUrl * @return */ public String getImgUrl(String fileUrl) { if (!StringUtils.isEmpty(fileUrl)) { String[] split = fileUrl.split( "/" ); return this .getUrl( this .filedir + split[split.length - 1 ]); } return null ; } /** * OSS * * @param instream * @param fileName * @return "" , MD5 */ public String uploadFile2OSS(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 = ossClient.putObject(bucketName, filedir + fileName, instream, objectMetadata); ret = putResult.getETag(); } catch (IOException e) { log.error(e.getMessage(), e); } finally { try { if (instream != null ) { instream.close(); } } catch (IOException e) { e.printStackTrace(); } } return ret; } /** * Description: OSS 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" ; } /** * url * * @param key * @return */ public String getUrl(String key) { // URL 10 3600l* 1000*24*365*10 Date expiration = new Date( new Date().getTime() + 3600l * 1000 * 24 * 365 * 10 ); // URL URL url = ossClient.generatePresignedUrl(bucketName, key, expiration); if (url != null ) { return url.toString(); } return null ; } }
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
다양한 언어의 JSON
JSON은 Javascript 표기법을 사용하여 데이터 구조를 레이아웃하는 데이터 형식입니다.
그러나 Javascript가 코드에서 이러한 구조를 나타낼 수 있는 유일한 언어는 아닙니다.
저는 일반적으로 '객체'{}...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.
"/bcis/api/headImgUpload.json" method= "post" enctype= "multipart/form-data" > "file" name= "file" > "submit" value= " " >
2.controller:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 @RequestMapping (value = "/headImgUpload.json" , method = RequestMethod.POST) @ResponseBody public Map headImgUpload(HttpServletRequest request,MultipartFile file) { Map value = new HashMap(); value.put( "success" , true ); value.put( "errorCode" , 0 ); value.put( "errorMsg" , "" ); try { String head = userService.updateHead(file, 4 ); // ,4 userId 。 value.put( "data" , head); } catch (IOException e) { e.printStackTrace(); value.put( "success" , false ); value.put( "errorCode" , 200 ); value.put( "errorMsg" , " " ); } return value; }
3. 서비스@Autowired
private OSSClientUtil ossClient;
1 2 3 4 5 6 7 8 9 10 @Override public String updateHead(MultipartFile file, long userId) throws IOException{ if (file == null || file.getSize() <= 0 ) { throw new ImgException( " " ); } String name = ossClient.uploadImg2Oss(file); String imgUrl = ossClient.getImgUrl(name); userDao.updateHead(userId, imgUrl); // return imgUrl; }
4. 업로드된 아리운의 도움말 클래스 OSSClientUtil
1 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 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 import java.io.*; import java.net.URL; import java.util.Date; import java.util.Random; import com.fndsoft.bcis.exception.ImgException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.aliyun.oss.OSSClient; import com.aliyun.oss.model.ObjectMetadata; import com.aliyun.oss.model.PutObjectResult; import org.springframework.util.StringUtils; import org.springframework.web.multipart.MultipartFile; /** * OSS * * @author YuanDuDu */ public class OSSClientUtil { Log log = LogFactory.getLog(OSSClientUtil. class ); // endpoint , region private String endpoint = " endpoint" ; // accessKey private String accessKeyId = " accessKeyId" ; private String accessKeySecret = " accessKeySecret" ; // private String bucketName = "bcis" ; // private String filedir = "data/" ; private OSSClient ossClient; public OSSClientUtil() { ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret); } /** * */ public void init() { ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret); } /** * */ public void destory() { ossClient.shutdown(); } /** * * * @param url */ public void uploadImg2Oss(String url) { File fileOnServer = new File(url); FileInputStream fin; try { fin = new FileInputStream(fileOnServer); String[] split = url.split( "/" ); this .uploadFile2OSS(fin, split[split.length - 1 ]); } catch (FileNotFoundException e) { throw new ImgException( " " ); } } public String uploadImg2Oss(MultipartFile file) { if (file.getSize() > 1024 * 1024 ) { throw new ImgException( " 1M!" ); } String originalFilename = file.getOriginalFilename(); String substring = originalFilename.substring(originalFilename.lastIndexOf( "." )).toLowerCase(); Random random = new Random(); String name = random.nextInt( 10000 ) + System.currentTimeMillis() + substring; try { InputStream inputStream = file.getInputStream(); this .uploadFile2OSS(inputStream, name); return name; } catch (Exception e) { throw new ImgException( " " ); } } /** * * * @param fileUrl * @return */ public String getImgUrl(String fileUrl) { if (!StringUtils.isEmpty(fileUrl)) { String[] split = fileUrl.split( "/" ); return this .getUrl( this .filedir + split[split.length - 1 ]); } return null ; } /** * OSS * * @param instream * @param fileName * @return "" , MD5 */ public String uploadFile2OSS(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 = ossClient.putObject(bucketName, filedir + fileName, instream, objectMetadata); ret = putResult.getETag(); } catch (IOException e) { log.error(e.getMessage(), e); } finally { try { if (instream != null ) { instream.close(); } } catch (IOException e) { e.printStackTrace(); } } return ret; } /** * Description: OSS 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" ; } /** * url * * @param key * @return */ public String getUrl(String key) { // URL 10 3600l* 1000*24*365*10 Date expiration = new Date( new Date().getTime() + 3600l * 1000 * 24 * 365 * 10 ); // URL URL url = ossClient.generatePresignedUrl(bucketName, key, expiration); if (url != null ) { return url.toString(); } return null ; } }이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
다양한 언어의 JSONJSON은 Javascript 표기법을 사용하여 데이터 구조를 레이아웃하는 데이터 형식입니다. 그러나 Javascript가 코드에서 이러한 구조를 나타낼 수 있는 유일한 언어는 아닙니다. 저는 일반적으로 '객체'{}...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.