oss不支持通过一个网络地址来上传图片,所以若想将网络上的图片上传到oss上需要走点弯路。
1、通过链接将图片下载到本地的一个文件夹下面
2、用oss上传该文件夹下的文件
3、上传完成后删除本地的文件
具体代码如下:
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
|
//获取当前项目的绝对路径 public static string gettomcatpath(){ string nowpath; string tempdir; nowpath=system.getproperty( "user.dir" ); tempdir=nowpath.replace( "bin" , "" ); //把bin 文件夹变到 webapps文件里面 return tempdir; } /** * 将图片下载下来后,上传到oss * @param imglink * @param downloadpath * @return * @throws exception */ private string downloadimaganduploadtooss(string imglink,string downloadpath) throws exception{ list<string> urllist= new arraylist<string>(); urllist.add(imglink); string imgname=dateutil.formatdate( new date(), "yyyymmddhhmmss" )+uuidutil.createuuid()+ ".jpg" ; downloadpicture(urllist,downloadpath,imgname); string key= "caralbum/" +imgname; string imgurl=ossobjectapi.genosspicurl(ossobjectapi.xi_an_bucket_name,ossobjectapi.xian_access_id,ossobjectapi.xian_access_key, "http://oss-cn-zhangjiakou.aliyuncs.com/" ,downloadpath+imgname,key); fileutil.delete(downloadpath+imgname); return imgurl; } /** * 传入要下载的图片的url列表,将url所对应的图片下载到本地 * @param urllist * @throws exception */ private void downloadpicture(list<string> urllist,string path,string imgname) throws exception { if (urllist== null ||urllist.size()== 0 ){ return ; } url url = null ; fileoutputstream fileoutputstream = null ; inputstream inputstream = null ; for (string urlstring : urllist) { try { url = new url(urlstring); httpurlconnection connection = (httpurlconnection) url.openconnection(); connection.addrequestproperty( "user-agent" , "mozilla/5.0 (windows nt 6.1; wow64; rv:55.0) gecko/20100101 firefox/55.0" ); connection.setconnecttimeout( 10 * 1000 ); connection.setreadtimeout( 15 * 1000 ); inputstream = connection.getinputstream(); byte [] buffer = new byte [ 1024 ]; int length; fileoutputstream= new fileoutputstream(path+ file.separator+ imgname); while ((length = inputstream.read(buffer)) != - 1 ) { fileoutputstream.write(buffer, 0 , length); } } catch (exception e) { e.printstacktrace(); } finally { inputstream.close(); fileoutputstream.flush(); fileoutputstream.close(); } } } |
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/qq_33556185/article/details/79152679