【问题标题】:Android Upload Image From Drawable To ServerAndroid 将图像从 Drawable 上传到服务器
【发布时间】:2020-11-19 18:18:26
【问题描述】:

嘿,我正在制作这个应用程序,用户在其中添加图像附件,然后将其发送到服务器。但附件不是强制性的,因此用户仍然可以将其发送到服务器而无需添加附件。如果用户不添加附件,它将发送默认图像。我想从drawable发送一个图像作为默认图像。我已经做了代码,但它不起作用。我的代码如下:

Resources resources = this.getResources();
        Uri otherPath = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + resources.getResourcePackageName(R.drawable.image) + '/' + resources.getResourceEntryName(R.drawable.eimage));
        String path = otherPath .toString();
        imageFile.setImageBitmap(BitmapFactory.decodeFile(path));

        File file1 = new File(path);
        RequestBody requestBody = RequestBody.create(MediaType.parse("*/*"), file1);
        MultipartBody.Part fileToUpload = MultipartBody.Part.createFormData("file", file1.getName(), requestBody);

它给我错误:“打开失败:ENOENT(没有这样的文件或目录)。 你有什么想法来完成这项工作吗? 对不起我的英语不好。

【问题讨论】:

  • 你想从drawable创建图像文件吗?
  • 是的,这就是我的意思。你有什么建议吗? @JyotishBiswas
  • 在答案部分添加了一个程序,如果您需要更多信息或任何其他方式,请告诉我

标签: java android upload multipart


【解决方案1】:

这里的 id 是你的可绘制资源的标识符。示例:R.drawable.profile_image

现在使用这个输入流你可以创建一个文件

try
{
    File f=new File("your file name");
    InputStream inputStream = getResources().openRawResource(id);
    OutputStream out=new FileOutputStream(f);
    byte buf[]=new byte[1024];
    int len;
    while((len=inputStream.read(buf))>0)
    out.write(buf,0,len);
    out.close();
    inputStream.close();
}
catch (IOException e){
}

【讨论】:

    猜你喜欢
    • 2011-02-02
    • 2015-03-29
    • 2011-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-17
    相关资源
    最近更新 更多