前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Retrofit 实现上传下载文件

Retrofit 实现上传下载文件

作者头像
张拭心 shixinzhang
发布2022-11-30 16:49:48
5080
发布2022-11-30 16:49:48
举报
文章被收录于专栏:拭心的安卓进阶之路

1.创建上传接口

1 2 3 4 5 6 7

public interface FileWebService {        @ Multipart      @ POST ( "/files" )      FileUploadedResponse upload ( @ Part ( "fileContent" ) TypedFile file ) ;   }

2.调用上传

1 2 3 4 5 6

File file = // create your File object here RestAdapter restAdapter = // create your RestAdapter String mimeType = "image/jpg" ; TypedFile fileToSend = new TypedFile ( mimeType , file ) ; FileWebService fileWebService = restAdapter . create ( FileWebService . class ) ; fileWebService . upload ( fileToSend ) ;

3.创建下载接口

1 2 3 4 5 6

public interface FileWebService {      @ GET ( "/files/{fileId}" )      @ Headers ( { "Content-Type: image/jpeg" } )      Response getFile ( @ Path ( "fileId" ) int fileId ) ;   }

4.调用 

1 2 3

int fileId = 123 ; Response response = fileWebService . getFile ( fileId ) ; byte [ ] bytes = FileHelper . getBytesFromStream ( response . getBody ( ) . in ( ) ) ;

 FileHelper.getBytesFromStream 代码如下:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

public static byte [ ] getBytesFromStream ( InputStream is ) throws IOException {   int len ; int size = 1024 ; byte [ ] buf ;   ByteArrayOutputStream bos = new ByteArrayOutputStream ( ) ; buf = new byte [ size ] ; while ( ( len = is . read ( buf , 0 , size ) ) != - 1 ) { bos . write ( buf , 0 , len ) ; } buf = bos . toByteArray ( ) ;   return buf ; }

保存到指定路径文件:

代码语言:javascript
复制
public static void saveBytesToFile(byte[] bytes,String path){
try{
	FileOutputStreamfileOuputStream=newFileOutputStream(path);
f	ileOuputStream.write(bytes);
}catch(FileNotFoundExceptione){
	e.printStackTrace();
}catch(IOExceptione){
	e.printStackTrace();
}finally{
         fileOuputStream.close();
        }
}

本文出自 Lac,转载时请注明出处及相应链接。 本文永久链接: http://www.xueyong.net.cn/archives/39

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2015-05-13,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档