volley 上传文件图片

public class FileUploadEntity {

    private static final String TAG = FileUploadEntity.class.getSimpleName();

    private static final String BOUNDARY ="__FILE_UPLOAD_ENTITY__";

    private ByteArrayOutputStream mOutputStream;
    public static HashMap<String,String> hashMap =new HashMap<>();
    static {
        hashMap.put("png" ,"image/png" );
        hashMap.put("gif" ,"image/gif" );
        hashMap.put("jpg" ,"image/jpeg" );
        hashMap.put("jpeg" ,"image/jpeg" );
        hashMap.put("bmp" ,"image/bmp" );
    }

    public FileUploadEntity() {
        mOutputStream =new ByteArrayOutputStream();

        try {
            writeFirstBoundary();
        }catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void writeFirstBoundary()throws IOException {
        VolleyLog.e("writeFirstBoundary");
        mOutputStream.write(("--" + BOUNDARY +"\r\n").getBytes());
        mOutputStream.write(("Content-Disposition: form-data; name=\"" +"name" +"\"\r\n\r\n").getBytes());
        mOutputStream.write("Content-Transfer-Encoding: binary\n\n".getBytes());
        mOutputStream.flush();
    }


    private void writeLastBoundary()throws IOException {
        VolleyLog.e("writeLastBoundary");
        mOutputStream.write(("\r\n--" + BOUNDARY +"--\r\n").getBytes());
    }
    /**
     * 获取文件扩展名
     * @return
     */
    public static String ext(String filename) {
        int index = filename.lastIndexOf(".");

        if (index == -1) {
            return null;
        }
        String result = filename.substring(index + 1);
        return result;
    }
    public void addFile(final String key,final File file) {
        VolleyLog.e("addFile");
        InputStream inputStream =null;
        try {
            mOutputStream.write(("\r\n--" + BOUNDARY +"\r\n").getBytes());

            StringBuilder stringBuilderContentDisposition =new StringBuilder();
            stringBuilderContentDisposition.append("Content-Disposition: ");
            stringBuilderContentDisposition.append("form-data; ");
            stringBuilderContentDisposition.append("name=\"" + key +"\"; ");
            String fileName = file.getName();
            if(!TextUtils.isEmpty(ContextUtils.getGameId())){
                fileName = ContextUtils.getGameId()+"_"+System.currentTimeMillis()+"."+ext(file.getName());
            }
            stringBuilderContentDisposition.append("filename=\"" + fileName +"\"\r\n");
            mOutputStream.write(stringBuilderContentDisposition.toString().getBytes());

            StringBuilder stringBuilderContentType =new StringBuilder();
            stringBuilderContentType.append("Content-Type: ");
            stringBuilderContentType.append(hashMap.get(ext(file.getName()).toLowerCase()));//"image/png"
            stringBuilderContentType.append("\r\n\r\n");
            mOutputStream.write(stringBuilderContentType.toString().getBytes());

            inputStream =new FileInputStream(file);
            final byte[] buffer =new byte[1024];
            int len =0;
            while ((len = inputStream.read(buffer)) != -1) {
                mOutputStream.write(buffer,0, len);
            }
            VolleyLog.e("===last====len --> %s", String.valueOf(len));

            mOutputStream.flush();
        }catch (FileNotFoundException e) {
            e.printStackTrace();
        }catch (IOException e) {
            e.printStackTrace();
        }finally {
            closeSilently(inputStream);
        }
    }

    private void closeSilently(Closeable closeable) {
        try {
            if (closeable !=null) {
                closeable.close();
            }
        }catch (final IOException e) {
            e.printStackTrace();
        }
    }


    public boolean isRepeatable() {
        return false;
    }


    public boolean isChunked() {
        return false;
    }


    public long getContentLength() {
        return mOutputStream.toByteArray().length;
    }


    public Header getContentType() {
        return new Header("Content-Type","multipart/form-data; boundary=" + BOUNDARY);
    }


    public Header getContentEncoding() {
        return null;
    }


    public InputStream getContent()throws IOException, UnsupportedOperationException {
        return new ByteArrayInputStream(mOutputStream.toByteArray());
    }


    public void writeTo(OutputStream outputStream)throws IOException {
        writeLastBoundary();
        outputStream.write(mOutputStream.toByteArray());
    }


    public boolean isStreaming() {
        return false;
    }

    public void consumeContent()throws IOException {

    }
}


public class FileUploadRequest extends Request<JSONObject>  {
    private final Response.Listener<JSONObject> mListener;

    private FileUploadEntity mFileUploadEntity = new FileUploadEntity();
    private Map<String, String> mHeaders = new HashMap<>();
    private long requestStartTs =0;
    public FileUploadRequest(String url, Response.Listener<JSONObject> listener, Response.ErrorListener errorListener) {
        this(Method.POST, url, listener, errorListener);
        requestStartTs = System.currentTimeMillis();
        setRetryPolicy(new DefaultRetryPolicy(
                10000,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
    }

    public FileUploadRequest(int method, String url, Response.Listener<JSONObject> listener, Response.ErrorListener errorListener) {
        super(method, url, errorListener);
        requestStartTs = System.currentTimeMillis();
        this.mListener = listener;
        setRetryPolicy(new DefaultRetryPolicy(
                20000,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
    }
    public void setAuth(String auth) {
        mHeaders.put("Authorization", auth);
    }
    public FileUploadEntity getFileUploadEntity() {
        return mFileUploadEntity;
    }

    @Override
    public String getBodyContentType() {
        return mFileUploadEntity.getContentType().getValue();
    }

    public void addHeader(String key, String value) {
        mHeaders.put(key, value);
    }

    @Override
    public Map<String, String> getHeaders() throws AuthFailureError {
        return mHeaders;
    }

    @Override
    public byte[] getBody() throws AuthFailureError {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        try {
            mFileUploadEntity.writeTo(outputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return outputStream.toByteArray();
    }

    @Override
    protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
        String parsed = "";
        try {
            parsed = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
            LogUtil.terminal(LogUtil.LogType.d, null, CGJsonRequest.class.getSimpleName()
                    , String.format("report original data:%s", TextUtils.isEmpty(parsed) ? "null" : parsed));
            return Response.success(new JSONObject(parsed), HttpHeaderParser.parseCacheHeaders(response));
        } catch (JSONException | UnsupportedEncodingException e) {
            e.printStackTrace();
            return Response.error(new ParseError(e));
        }
    }

    @Override
    protected void deliverResponse(JSONObject response) {
        if (mListener != null) {
            mListener.onResponse(response);
        }
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容