美文网首页
okHttp异步上传图片到服务器得到Internal serve

okHttp异步上传图片到服务器得到Internal serve

作者: YouMyGod | 来源:发表于2019-01-21 23:04 被阅读0次

这是一个巨坑,先上源码:

//Android


    /**
     * 上传图像到服务器
     * @param img
     */
      public void  uploadImgToServer(File img) throws UnsupportedEncodingException {
            sp = mContext.getSharedPreferences("member_log", Context.MODE_PRIVATE);
            String fileName = sp.getString("username","");
            String finalName = URLEncoder.encode(fileName,"utf-8");//解析中文到GBK编码

            MediaType MEDIA_TYPE_JPG = MediaType.parse("application/x-www-form-urlencoded");
            RequestBody requestBody = MultipartBody.create(MEDIA_TYPE_JPG,img);
//            String finalName = getValueEncoded(fileName);
          // 把我坑的一上午你妈的,老子一致在NetUtils
          // 里面转悠,没有想到你是发送到服务器的最后一步。
        MultipartBody.Builder builder = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("title","Logo")
                .addFormDataPart("img",finalName+".jpg", //封装上传图片的参数
                        requestBody);


        //ReqestBody中要携带参数
        RequestBody multipartBody = builder.build();//Build a instance of RequestBody

        String url = "http://192.168.1.117:8080/polls/uploadHeadImg/";
        Request request = new Request.Builder()
                .url(url)
//                .addHeader("Accept","text/plain")
                .addHeader("Accept-Charset", "UTF-8")
//                .addHeader("Content-Type","application/x-www-form-urlencoded; charset=utf-8")
                .post(multipartBody)
                .build();

        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("TAG","onFaile:" +e);
                Thread thread = new Thread(() -> {
                    Looper.prepare();
                    Toast.makeText(mContext,"上传失败",Toast.LENGTH_LONG).show();
                    Looper.loop();
                });

                thread.start();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                    Log.e("TAG","success");
                    if(!response.isSuccessful()){

                        Thread thread = new Thread(() -> {
                                Looper.prepare();
                                Toast.makeText(mContext,"上传成功,请求失败",
                                        Toast.LENGTH_LONG).show();
                                Looper.loop();

                            });
                            thread.start();
                 }else{

                        Thread thread = new Thread(() -> {
                            Looper.prepare();
                            try {
                                Toast.makeText(mContext,"上传成功,返回信息:"+response.body().string(),
                                        Toast.LENGTH_LONG).show();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                            Looper.loop();


                        });
                        thread.start();
                    }
            }
        });

    }

贴出Django代码:

# Add member head portrait
@csrf_exempt
def uploadHeadImg(request):

    source = request.FILES.get('img')
    if source:
        firstName = source.name
        secondName = os.path.splitext(firstName)[0]#Double check trim the blank.
        finalName = unquote(secondName)
        source.name = finalName+".jpg"
        member = Member.objects.get(user_name=finalName)
        member.attribute_set.create(head_img=source, name=finalName, last_login_time=timezone.now())
       

        return HttpResponse(source.name+"upload success", content_type="text/plain")
    else:
        return HttpResponse(source.name+"Failed", content_type="text/plain")

以上代码亲测upload server picture没有任何问题,可是奇怪的现象出现了,在onResponse中 response.code() 得到http error code 500,我找了N多个博文,大多数都是在StackOverflow上面,都说的要么很深,要么驴头不对马嘴,都没有解决。最后发现,问题出现在你的服务器上是否存在文件,如果不存在就需要用create的方式,如果存在了,注意:就一定要用我列举的第二种方式,要不然就会一直返回500如下:

  • 改变model的存储方式需要判断,正确的代码如下:
# Add member head portrait
@csrf_exempt
def uploadHeadImg(request):

    source = request.FILES.get('img')
    if source:
        firstName = source.name
        secondName = os.path.splitext(firstName)[0]#Double check trim the blank.
        finalName = unquote(secondName)
        source.name = finalName+".jpg"
        member = Member.objects.get(user_name=finalName)
              if  member.attribute_set.all().exists():#先判断查询集里面是否有模型对象如果没有说明是第一次设置头像,并不是修改头像。
                   attribute = member.attribute_set.get(img_name=finalName)
                   attribute.head_img = source
                   attribute.img_name = finalName
                   attribute.save()
              else:
                   member.attribute_set.create(img_name=finalName, head_img=source, last_login_time=datetime.now())#第一次修改头像,就必须用这种方法

        return HttpResponse(json.dumps(
            {"headImg_path":"httP://127.168.1.117:8080/midea/headImg/"+source.name}
        ), content_type='application/json; charset=utf-8')
    else:
        return HttpResponse(json.dumps({
            'error_code':100,
            'result':'request_error'
        }))

相关文章

网友评论

      本文标题:okHttp异步上传图片到服务器得到Internal serve

      本文链接:https://www.haomeiwen.com/subject/ziqkjqtx.html