服务器接收pdf文件失败,从服务器接收PDF格式的回应

对于大家想知道人类的方式来做到这一点,这里是我的工作流程:

1 - 生成PDF文件,抢个字节,并将其转换为base64字符串后。

我可以很容易地做到这一点与使用Python pyfpdf lib和使用Django作为后端:

import base64

def my_view(request):

pdf = MyCustomPDF()

pdf.add_page()

pdf.set_margins(12,3,3)

pdf.render() # PDF is ready to be saved

b = pdf.output('output.pdf','B') # got the PDF as a byte array

return JsonResponse(

{

"name" : "my_doc.pdf",

"content64" : base64.b64encode(b).decode('utf8')

}

)

记住这个例子可以用其他后端做/库!

2 - 在您的Android项目上设置一个字符串您希望用于接收PDF回复/回叫的模型字段。所以我们的PDF将会像这样到达。

{

"name" : "my_doc.pdf",

"content64" : "aGVsbG8gd29ybGQ="

}

所以在Java中,我们可以设置自定义POJO

class PDF{

private String name;

private String content64;

// (...)

}

3 - 基于64位将是一个简单的字符串!要获得真正的文件作为字节只写这样

class PDF{

private String name;

private String content64;

// (...)

public byte[] content64AsByteArray(){ // Helps you convert string to byte formats :B

return Base64.decode(content64,Base64.DEFAULT);

}

public String save(String path) {

try {

String path = Environment.getExternalStorageDirectory() + "/" + path;

File f1 = new File(path);

OutputStream out = null;

out = new FileOutputStream(path + "/" + this.name);

out.write(this.content64AsByteArray());

out.close();

} catch (FileNotFoundException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}

return this.path; // I like to return it because i can use it to start a "open file" intent

}

}

4例行 - 接收回调会是这样与改造

pdfCallback = new Callback() {

@Override public void success(PDF pdf, Response response) {

if (response.getStatus() == 200) {

String pathToPDF = pdf.save() // save PDF

}

}

@Override public void failure(RetrofitError error) {

(...)

}

}

MyAPI.callbacks.getPDF((...), pdfCallback);

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值