码迷,mamicode.com
首页 > 移动开发 > 详细

java接受安卓及ios App上传的图片,并保存到阿里OSS

时间:2018-04-04 23:42:37      阅读:568      评论:0      收藏:0      [点我收藏+]

标签:空字符串   构造   初始化   ada   文件夹   org   generator   ios   app   

做后台的时候,写了两个方法,分别用来获取安卓和苹果IOS端上传的头像,保存到阿里云OSS图片存储服务器上。(SMM框架)

安卓及H5版本:

技术分享图片
 1  /**
 2      * 上传用户头像
 3      */
 4     @RequestMapping("/uploadPhoto")
 5     public R uploadPhoto(@RequestParam("imgFile") MultipartFile imgFile, HttpServletRequest req) throws Exception {
 6         if (imgFile.isEmpty()) {
 7             throw new RRException("上传文件不能为空");
 8         }
 9         
10         Integer uid = WebUtils.getUid(req);
11         WfMemberEntity member = memberService.queryObject(uid);
12         
13         String newsUrl = "";
14         if (!((MultipartFile) imgFile).isEmpty()) {
15             try {
16                 newsUrl = OSSUtil.addFile(imgFile, "head", Constants.IGM_BUCKET);
17                 
18             } catch (IOException e) {
19                 e.printStackTrace();
20             }
21         }else {
22             return R.error("上传图片不可为空");
23         }
24         if(member.getHeadimage() == null) {
25              member.setHeadimage(newsUrl);
26              member.setThumbimg(newsUrl);
27              memberService.update(member);
28         }else {
29             // 删除原来图片
30             OSSUtil.delete(member.getHeadimage(), Constants.IGM_BUCKET);
31             member.setHeadimage(newsUrl);
32             member.setThumbimg(newsUrl);
33             memberService.update(member);
34         }
35         System.out.println("*************************************头像路径: "+newsUrl+"***************************************");
36         return R.ok().put("url", newsUrl);
37     }
View Code

对应的苹果图片上传版本:

技术分享图片
 1  @RequestMapping("/iosUpload")  
 2    public R iosUpload(HttpServletRequest req){  
 3         
 4         Integer uid = WebUtils.getUid(req);
 5         WfMemberEntity member = memberService.queryObject(uid);
 6         
 7         String image = req.getParameter("image");
 8           // 将base64 转 字节数组
 9         Base64 base = new Base64();
10         byte[] decode = base.decode(image);
11 
12         // 定义图片输入流
13         InputStream fin = new ByteArrayInputStream(decode);
14         
15         String newsUrl = "";
16         try {
17             newsUrl = OSSUtil.putFile(fin, "head", Constants.IGM_BUCKET);
18         } catch (IOException e) {
19             e.printStackTrace();
20         }
21         if(member.getHeadimage() == null) {
22              member.setHeadimage(newsUrl);
23              member.setThumbimg(newsUrl);
24              memberService.update(member);
25         }else {
26             // 删除原来图片
27             OSSUtil.delete(member.getHeadimage(), Constants.IGM_BUCKET);
28             member.setHeadimage(newsUrl);
29             member.setThumbimg(newsUrl);
30             memberService.update(member);
31         }
32         System.out.println("*************************************头像路径: "+newsUrl+"***************************************");
33         return R.ok().put("url", newsUrl);
34     }
View Code

对应的OSS上传工具:

技术分享图片
  1 package com.wfcm.utils;
  2 
  3 import java.io.File;
  4 import java.io.FileInputStream;
  5 import java.io.FileNotFoundException;
  6 import java.io.IOException;
  7 import java.io.InputStream;
  8 import java.util.ArrayList;
  9 import java.util.List;
 10 
 11 import org.springframework.web.multipart.MultipartFile;
 12 import org.springframework.web.multipart.commons.CommonsMultipartFile;
 13 
 14 import com.aliyun.oss.OSSClient;
 15 import com.aliyun.oss.model.ListObjectsRequest;
 16 import com.aliyun.oss.model.OSSObject;
 17 import com.aliyun.oss.model.OSSObjectSummary;
 18 import com.aliyun.oss.model.ObjectListing;
 19 import com.aliyun.oss.model.ObjectMetadata;
 20 import com.wfcm.utils.UUIDGenerator;
 21 
 22 
 23 /**
 24  * 阿里云分布式存储工具类
 25  * @author lyinlong
 26  *
 27  */
 28 public class OSSUtil {
 29 
 30     //初始化client
 31     static OSSClient client = new OSSClient(Constants.OSS_ENDPOINT,Constants.OSS_ACCESS_ID, Constants.OSS_ACCESS_KEY);
 32 
 33     /**
 34      * 获取指定文件夹下的文件列表
 35      * @param folderName 文件夹名称(如果获取当前所有, 空字符串)
 36      * @return 文件的所有key
 37      * @throws IOException
 38      */
 39     public static List<String> listBybucket(String bucketName ,String folderName) throws IOException{
 40         // 构造ListObjectsRequest请求
 41         ListObjectsRequest listObjectsRequest = new ListObjectsRequest(bucketName);
 42 
 43         // 递归列出fun目录下的所有文件
 44         listObjectsRequest.setPrefix(folderName);
 45 
 46         ObjectListing listing = client.listObjects(listObjectsRequest);
 47 
 48         List<String> keys = new ArrayList<>();
 49 
 50         // 遍历所有Object
 51         for (OSSObjectSummary objectSummary : listing.getObjectSummaries()) {
 52             keys.add(objectSummary.getKey());
 53         }
 54         return keys;
 55     }
 56 
 57     /**
 58      * 通过key获取指定的Object
 59      * @param key
 60      * @return
 61      */
 62     public static InputStream getObject(String bucketName, String key){
 63         OSSObject object = client.getObject(bucketName, key);
 64         InputStream objectContent = object.getObjectContent();
 65 
 66         return objectContent;
 67     }
 68 
 69     /**
 70      * 添加一个文件到指定文件夹
 71      * @param file
 72      * @param folder
 73      * @return 该文件的Key(文件的唯一标识)
 74      * @throws FileNotFoundException
 75      */
 76     public static String putObject(File file , String folder , String bucketName) throws FileNotFoundException{
 77          // 获取指定文件的输入流
 78         InputStream content = new FileInputStream(file);
 79 
 80         // 创建上传Object的Metadata
 81         ObjectMetadata meta = new ObjectMetadata();
 82 
 83         // 必须设置ContentLength
 84         meta.setContentLength(file.length());
 85 
 86         String uuid = UUIDGenerator.getUUID(false);
 87 
 88         client.putObject(bucketName, folder+"/"+uuid, content, meta);
 89 
 90         return uuid;
 91     }
 92 
 93     public static String putFile(InputStream content  , String folder , String bucketName) throws FileNotFoundException{
 94          // 获取指定文件的输入流
 95         //InputStream content = new FileInputStream(file);
 96 
 97         // 创建上传Object的Metadata
 98         ObjectMetadata meta = new ObjectMetadata();
 99 
100         // 必须设置ContentLength
101         try {
102             meta.setContentLength(content.available());
103         } catch (IOException e) {
104             // TODO Auto-generated catch block
105             e.printStackTrace();
106         }
107 
108         String uuid = UUIDGenerator.getUUID(false);
109         client.putObject(bucketName, folder+"/"+uuid+".jpg", content, meta);
110 
111         return folder+"/"+uuid+".jpg";
112     }
113     
114     public static String addFile(Object file , String folder , String bucketName) throws IOException{
115          InputStream content  = null;
116          ObjectMetadata meta = null;
117          String  extension = "";
118         if(file!=null){
119             if(file instanceof CommonsMultipartFile){
120                 CommonsMultipartFile file1  = (CommonsMultipartFile)file;
121                 //文件扩展名
122                  String fileName = file1.getOriginalFilename();
123                  if(fileName.lastIndexOf(".")!=-1){
124                      extension = fileName.substring(fileName.lastIndexOf("."),fileName.length());
125                  }
126                  
127                 // 获取指定文件的输入流
128                   content =file1.getInputStream();
129                     // 创建上传Object的Metadata
130                    meta = new ObjectMetadata();
131                     // 必须设置ContentLength
132                     meta.setContentLength(file1.getSize());
133                   // 设置content type  
134                     String strContentType = file1.getContentType();  
135                     meta.setContentType(strContentType);  
136             }
137             else if(file instanceof MultipartFile){
138                 MultipartFile    file2 = (MultipartFile)file;
139                  String fileName = file2.getOriginalFilename();
140                  if(fileName.lastIndexOf(".")!=-1){
141                      extension = fileName.substring(fileName.lastIndexOf("."),fileName.length());
142                  }
143                 // 获取指定文件的输入流
144                   content =file2.getInputStream();
145                     // 创建上传Object的Metadata
146                    meta = new ObjectMetadata();
147                     // 必须设置ContentLength
148                     meta.setContentLength(file2.getSize());
149             }
150             else if(file instanceof File){
151                 File file3 = (File)file;
152                 //文件扩展名
153                  String fileName = file3.getName();
154                  if(fileName.lastIndexOf(".")!=-1){
155                      extension = fileName.substring(fileName.lastIndexOf("."),fileName.length());
156                  }
157                 
158                 // 获取指定文件的输入流
159                   content =new FileInputStream(file3);
160                     // 创建上传Object的Metadata
161                   meta = new ObjectMetadata();
162                     // 必须设置ContentLength
163                   meta.setContentLength(file3.length());
164             }
165             else {
166                 return null;
167             }
168         }
169         String uuid = UUIDGenerator.getUUID(false);
170 
171         client.putObject(bucketName, folder+"/"+uuid+extension, content, meta);
172 
173         return folder+"/"+uuid+extension;
174     }
175     
176     /**
177      * 删除指定的文件
178      * @param key
179      */
180     public static void delete(String key,String bucketName){
181 
182         client.deleteObject(bucketName, key);
183     }
184 
185     /**
186      * 新建文件桶
187      * @param bucketName
188      */
189     public static void createBucket(String bucketName){
190         client.createBucket(bucketName);
191     }
192 
193 }
View Code

 

java接受安卓及ios App上传的图片,并保存到阿里OSS

标签:空字符串   构造   初始化   ada   文件夹   org   generator   ios   app   

原文地址:https://www.cnblogs.com/hero123/p/8719111.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!