改造:在 POST @body 中上传图片

Posted

技术标签:

【中文标题】改造:在 POST @body 中上传图片【英文标题】:Retrofit: Image Upload in 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

我在这里错过了什么?

提前谢谢你

【问题讨论】:

【参考方案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);
    

【讨论】:

以上是关于改造:在 POST @body 中上传图片的主要内容,如果未能解决你的问题,请参考以下文章

如何使用 Alamofire (post) 上传图片?

koa实现简单图片上传

如何从android改造上传图像到服务器

改造图片上传无法处理的实体错误

改造vue-quill-editor: 结合element-ui上传图片到服务器

表单上传图片报错(解决方案):413 Request Entity Too Large