【问题标题】:Retrofit: Image Upload in POST @body改造:在 POST @body 中上传图片
【发布时间】:2015-09-16 19:08:18
【问题描述】:

经过数小时的搜索和尝试不同的解决方案后,我放弃了,我正在寻求一些指导,如果可能的话,提供一些示例。这是问题所在:我有一个具有图片属性的类。我正在使用 Retrofit,我想将图像作为 HTTP POST 正文的一部分发送,但我收到了一个错误。下面是代码和错误。

提前感谢您的帮助。

POJO 类:

public class Class1 {

@SerializedName("Picture")
private Bitmap mPicture;

@SerializedName("Giver")
public Integer mGiver;

public String getPicture() {
    return mPicture;
}

public void setPicture (Bitmap picture) {
    this.mPicture = picture;
}

public String getLaboratory() {
    return mLaboratory;
}

public void setLaboratory(String laboratory) {
    this.mLaboratory = laboratory;
}

活动:

    mClass1.setPicture(mImageBitmap);
    mClass1DAO.insertClass1(mClass1, new Callback<Integer>() {
        @Override
        public void success(Integer uid, Response response) {
            mClass1.setUID(uid);
            progressDialog.dismiss();
            Toast.makeText(getApplicationContext(), R.string.msgThankYou, Toast.LENGTH_LONG).show();
            dispatchNavigationDrawerActivity();
        }

        @Override
        public void failure(RetrofitError error) {
            progressDialog.dismiss();
            showErrorDialog(error.getLocalizedMessage());
        }
    });

API

@POST("/Service.svc/Insert")
void insert(@Body Class1 class1, Callback<Integer> cb);

c#中的WebService

    [OperationContract]
    [WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.Bare, RequestFormat = WebMessageFormat.Json,
    ResponseFormat = WebMessageFormat.Json, UriTemplate = "InsertMedicineToDonate")]
    Int32 insertMedicineToDonate(MedicineToDonate medicineToDonate);

    //insertMedicineToDonate
    public Int32 insertMedicineToDonate(MedicineToDonate medicineToDonate)
    {
        UserService mUserService = new UserService();

        if (mUserService.isUserAuthorized())
        {
            return this.insertMedicineToDonateAuth(medicineToDonate);

        }
        else
        {
            errorDetail = new CustomHttpError(003);
            throw new WebFaultException<CustomHttpError>(errorDetail, HttpStatusCode.Forbidden);
        }

    }

Web 服务 POJO 类

    namespace DoarMed
{
    [DataContract]
    public class MedicineToDonate
    {
        [DataMember]
        public Int32 UID { get; set; }
        [DataMember]
        public Bitmap Picture { get; set; }

错误

在调试中打开类查看属性都正确但图片错误。

请看下面的图片信息:

-       Picture {System.Drawing.Bitmap} System.Drawing.Bitmap
+       Flags   '((System.Drawing.Image)(medicineToDonate.Picture)).Flags' threw an exception of type 'System.ArgumentException'    int {System.ArgumentException}
+       FrameDimensionsList '((System.Drawing.Image)(medicineToDonate.Picture)).FrameDimensionsList' threw an exception of type 'System.ArgumentException'  System.Guid[] {System.ArgumentException}
+       Height  '((System.Drawing.Image)(medicineToDonate.Picture)).Height' threw an exception of type 'System.ArgumentException'   int {System.ArgumentException}

等等

当我尝试将图片保存到数据库时,代码会抛出 System.ArgumentException

我在这里错过了什么?

提前谢谢你

【问题讨论】:

    标签: image post upload retrofit wcf-rest


    【解决方案1】:

    这是解决方案,经过 3 天的尝试。我希望它可以节省您的时间。如果它确实节省了您的时间,请给我 +1。

    客户端安卓

    public class MedicineToDonate {
    @SerializedName("Picture")
    private String mPicture;
    @SerializedName("DateTimeInsert")
    public Long mDateTimeInsert;
    
    public Bitmap getPicture() {
        return Global.convertStringToBitmap(mPicture);
    }
    
    public void setPicture(Bitmap picture) {
        this.mPicture = Global.convertBitmapToString(picture);
    }
    

    改造

        mMedicineToDonateDAO.getGiverAllMedicineToDonate(mGlobal.getUserUID(), new Callback<List<MedicineToDonate>>() {
            @Override
            public void success(List<MedicineToDonate> mMedicineToDonateList, Response response) {
                if (mMedicineToDonateList != null) {
                    for (int i = 1; i <= mMedicineToDonateList.size(); i++) {
                        mMedicineToDonate = mMedicineToDonateList.get(i - 1);
                        mAdapter.add(mMedicineToDonate);
                    }
                }
                progressDialog.dismiss();
                Fragment mFragment = mFragmentManager.findFragmentByTag(Global.OPTION_DONATE);
                FragmentTransaction ft = mFragmentManager.beginTransaction();
                ft.detach(mFragment)
                        .attach(mFragment)
                        .commit();
                mFragmentManager.executePendingTransactions();
            }
    
            @Override
            public void failure(RetrofitError error) {
                progressDialog.dismiss();
                showErrorDialog(error.getLocalizedMessage());
            }
        });
    

    全球

        public static String convertBitmapToString(Bitmap imageBitmap){
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        if(imageBitmap != null) {
            imageBitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
            byte[] byteArray = stream.toByteArray();
            return Base64.encodeToString(byteArray, Base64.URL_SAFE);
        }else{
            return null;
        }
    }
    
    public static Bitmap convertStringToBitmap (String encodedString) {
        try {
            byte[] data = Base64.decode(encodedString, Base64.URL_SAFE);
            return BitmapFactory.decodeByteArray(data, 0, data.length);
        } catch(Exception e) {
            e.getMessage();
            return null;
        }
    }
    

    服务器端 (C#/IIS/Postgresql)

    Class
        [DataContract]
        public class MedicineToDonate
        {
        [DataMember]
        public string Picture { get; set; }
        [DataMember]
        public Int64 DateTimeInsert { get; set; }
        [DataMember]
    
    INSERT:
                NpgsqlParameter addPictureParameter = new NpgsqlParameter("@" + Global.MEDICINETODONATE_COL_picture, NpgsqlDbType.Bytea);
            byte[] byteArrayPicture = Global.convertStringToByteArray(medicineToDonate.Picture);
            addPictureParameter.Value = byteArrayPicture;
    
    SELECT:
            byte [] pictureByteArray = (byte[]) reader[12];
    mMedicineToDonate.Picture = Global.convertByteArrayToString(pictureByteArray);
    

    全球

        public static string convertByteArrayToString(byte[] bytes)
        {
            char[] chars = new char[bytes.Length / sizeof(char)];
            System.Buffer.BlockCopy(bytes, 0, chars, 0, bytes.Length);
            return new string(chars);
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-04-27
      • 2019-07-19
      • 2018-12-08
      • 1970-01-01
      • 2015-08-22
      • 2020-05-13
      • 2021-05-08
      • 2015-04-05
      相关资源
      最近更新 更多