如何在Android中使用`Content-Type:multipart / form-data`上传文件

时间:2017-02-22 08:11:16

标签: android file-upload android-volley multipartform-data

我想将数据上传到用ASP.Net编写的后端API。标题设置为<!DOCTYPE html> <html lang='en'> <head> <meta charset='utf-8' /> <script type='text/javascript' src='OpenLayers.js'></script> <script type='text/javascript'> var map; var vector_layer; function init() { //Create a map with an empty array of controls map = new OpenLayers.Map('map_element'); //Create a base layer var wms_layer = new OpenLayers.Layer.WMS( 'OpenLayers WMS', 'http://vmap0.tiles.osgeo.org/wms/vmap0', {layers: 'basic'}, {} ); map.addLayer(wms_layer); //Add vector layer vector_layer = new OpenLayers.Layer.Vector('Settlement Vector Layer'); map.addLayer(vector_layer); var settlement_values = { 4: 'circle' } //Create some points for(var i=0; i<20; i++){ vector_layer.addFeatures([new OpenLayers.Feature.Vector( new OpenLayers.Geometry.Point( (Math.floor(Math.random() * 360) - 180), (Math.floor(Math.random() * 180) - 90) ), { 'settlement_type': settlement_values[(Math.floor(Math.random() * 5))] } )]); } //Create a style map object var vector_style_map = new OpenLayers.StyleMap({}); //ADD RULES //We need to create a 'lookup table' that contains the desired values // and corresponding symbolizer var symbolizers_lookup = { 'circle': { 'fillColor': '#336699','fillOpacity':.8, 'pointRadius':50, 'strokeColor': '#003366', 'strokeWidth':2 } } //Now, call addUniqueValueRules and pass in the symbolizer lookups vector_style_map.addUniqueValueRules('default', 'settlement_type', symbolizers_lookup); //Add the style map to the vector layer vector_layer.styleMap = vector_style_map; if(!map.getCenter()){ map.zoomToMaxExtent(); } } </script> </head> <body onload='init();'> <div id='map_element' style='width: 600px; height: 600px;'></div> </body> </html>,然后我使用Postman测试图像上传,如下图所示

enter image description here

这就是Json的工作和回应。

Content-Type: multipart-form-data

作为回应的标题是

enter image description here

接下来,我在Android代码中使用它在应用程序中构建图像上传。我实现了{ "image": "http://192.168.100.249/api/images/download/2" } ,代码就像这样

MultipartRequest

依赖:

class MultipartRequest(url: String, errorListener: Response.ErrorListener, listener: Response.Listener<String>, realPath: String) : Request<String>(Method.POST, url, errorListener) {
    private val builder = MultipartEntityBuilder.create()!!
    private var entity: com.belladati.httpclientandroidlib.HttpEntity? = null

    private val FILE_PART_NAME = "file"

    private var mListener: Response.Listener<String>? = null

    init {
        builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
        try {
            builder.addPart(FILE_PART_NAME, FileBody(File(realPath)))
        } catch (e: UnsupportedEncodingException) {
            VolleyLog.e("UnsupportedEncodingException")
        }
        builder.setLaxMode().setBoundary("xx").setCharset(Charset.forName("UTF-8"))
        entity = builder.build()

        mListener = listener
    }

    @Throws(AuthFailureError::class)
    override fun getHeaders(): Map<String, String> {
        val headers: MutableMap<String, String> = mutableMapOf()

        headers.put("Content-Type", "multipart/form-data")

        return headers
    }

    @Throws(AuthFailureError::class)
    override fun getBody(): ByteArray {
        val bos = ByteArrayOutputStream()
        try {
            entity!!.writeTo(bos)
        } catch (e: IOException) {
            VolleyLog.e("IOException writing to ByteArrayOutputStream")
        }
        return bos.toByteArray()
    }

    override fun getBodyContentType(): String {
        return "multipart/form-data"
    }

    override fun parseNetworkResponse(response: NetworkResponse?): Response<String> {
        return Response.success(response!!.data.toString(), cacheEntry)
    }

    override fun deliverResponse(response: String?) {
        mListener!!.onResponse(response)
    }
}

并在compile 'org.apache.httpcomponents:httpcore:4.3.2' compile group: 'com.belladati', name: 'httpclientandroidlib', version: '4.3.0' 中,我添加了访问设备中文件的权限。

AndroidManifest.xml

最后,我写了这段代码来做上传过程。

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

, 其中val mQueue: RequestQueue = Volley.newRequestQueue(context) val imageUploadReq = MultipartRequest(url, Response.ErrorListener { error -> mQueue.stop()}, Response.Listener<String> { response -> mQueue.stop() }, realPath) mQueue.add(imageUploadReq) realPath的图像路径。

我调试时无法上传图像文件,响应为external/abc.jpg。我的代码出了什么问题。欢迎任何更正。

0 个答案:

没有答案