首页 \ 问答 \ 使用Google Volley上传图片(Upload an image using Google Volley)

使用Google Volley上传图片(Upload an image using Google Volley)

我需要将应用程序中正在开发的图像上传到服务器,并且想知道如何使用Google Volley开发多部分请求以加载图像。

谢谢


I would need to upload an image from the application, that I'm developing, to the server and I would like to know how I can develop the Multipart Request to load the image using Google Volley.

Thanks


原文:https://stackoverflow.com/questions/29430599
更新时间:2019-06-22 04:58

最满意答案

我有一个例子可以通过Google Volley上传图片。 看一看:

package net.colaborativa.exampleapp.api;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;

import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.HttpHeaderParser;

public class PhotoMultipartRequest<T> extends Request<T> {


private static final String FILE_PART_NAME = "file";

private MultipartEntityBuilder mBuilder = MultipartEntityBuilder.create();
private final Response.Listener<T> mListener;
private final File mImageFile;
protected Map<String, String> headers;

public PhotoMultipartRequest(String url, ErrorListener errorListener, Listener<T> listener, File imageFile){
    super(Method.POST, url, errorListener);

    mListener = listener;
    mImageFile = imageFile;

    buildMultipartEntity();
}

@Override
public Map<String, String> getHeaders() throws AuthFailureError {
    Map<String, String> headers = super.getHeaders();

    if (headers == null
            || headers.equals(Collections.emptyMap())) {
        headers = new HashMap<String, String>();
    }

    headers.put("Accept", "application/json");

    return headers;
}

private void buildMultipartEntity(){
    mBuilder.addBinaryBody(FILE_PART_NAME, mImageFile, ContentType.create("image/jpeg"), mImageFile.getName());
    mBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    mBuilder.setLaxMode().setBoundary("xx").setCharset(Charset.forName("UTF-8"));
}

@Override
public String getBodyContentType(){
    String contentTypeHeader = mBuilder.build().getContentType().getValue();
    return contentTypeHeader;
}

@Override
public byte[] getBody() throws AuthFailureError{
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    try {
        mBuilder.build().writeTo(bos);
    } catch (IOException e) {
        VolleyLog.e("IOException writing to ByteArrayOutputStream bos, building the multipart request.");
    }

    return bos.toByteArray();
}

@Override
protected Response<T> parseNetworkResponse(NetworkResponse response) {
    T result = null;
    return Response.success(result, HttpHeaderParser.parseCacheHeaders(response));
}

@Override
protected void deliverResponse(T response) {
    mListener.onResponse(response);
}
}

你可以像这样使用它:

RequestQueue mQueue = Volley.newRequestQueue(context);
PhotoMultipartRequest imageUploadReq = new PhotoMultipartRequest(url, ErrorListener, Listener, imageFile);
mQueue.add(imageUploadReq);

我希望这些代码能激励你。


I have an example to upload images by Google Volley. Take a look:

package net.colaborativa.exampleapp.api;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;

import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.HttpHeaderParser;

public class PhotoMultipartRequest<T> extends Request<T> {


private static final String FILE_PART_NAME = "file";

private MultipartEntityBuilder mBuilder = MultipartEntityBuilder.create();
private final Response.Listener<T> mListener;
private final File mImageFile;
protected Map<String, String> headers;

public PhotoMultipartRequest(String url, ErrorListener errorListener, Listener<T> listener, File imageFile){
    super(Method.POST, url, errorListener);

    mListener = listener;
    mImageFile = imageFile;

    buildMultipartEntity();
}

@Override
public Map<String, String> getHeaders() throws AuthFailureError {
    Map<String, String> headers = super.getHeaders();

    if (headers == null
            || headers.equals(Collections.emptyMap())) {
        headers = new HashMap<String, String>();
    }

    headers.put("Accept", "application/json");

    return headers;
}

private void buildMultipartEntity(){
    mBuilder.addBinaryBody(FILE_PART_NAME, mImageFile, ContentType.create("image/jpeg"), mImageFile.getName());
    mBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    mBuilder.setLaxMode().setBoundary("xx").setCharset(Charset.forName("UTF-8"));
}

@Override
public String getBodyContentType(){
    String contentTypeHeader = mBuilder.build().getContentType().getValue();
    return contentTypeHeader;
}

@Override
public byte[] getBody() throws AuthFailureError{
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    try {
        mBuilder.build().writeTo(bos);
    } catch (IOException e) {
        VolleyLog.e("IOException writing to ByteArrayOutputStream bos, building the multipart request.");
    }

    return bos.toByteArray();
}

@Override
protected Response<T> parseNetworkResponse(NetworkResponse response) {
    T result = null;
    return Response.success(result, HttpHeaderParser.parseCacheHeaders(response));
}

@Override
protected void deliverResponse(T response) {
    mListener.onResponse(response);
}
}

And you can use it like this:

RequestQueue mQueue = Volley.newRequestQueue(context);
PhotoMultipartRequest imageUploadReq = new PhotoMultipartRequest(url, ErrorListener, Listener, imageFile);
mQueue.add(imageUploadReq);

I hope these codes will inspire you.

2015-07-17

相关问答

更多

如何使用Android Volley API?(How do you use the Android Volley API?)

编辑:终于在这里是关于“Volley图书馆” 的官方培训 我发现了一些有关Volley图书馆的例子 Ognyan Bankov的6个例子 : 简单的请求 JSON请求 Gson请求 图像加载 与较新的外部HttpClient(4.2.3) 具有自签名SSL证书。 Paresh Mayani的一个很好的简单例子 另一个例子是HARDIK TRIVEDI ( 新 ) Android由Ravi Tamada 与Volley Library一起工作 希望这可以帮助你 Edit: finally here ...

错误:package com.android.volley不存在(error: package com.android.volley does not exist)

我必须在build.gradle下将compile project(':volley')到我的依赖项中 所以最终的代码是 dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) compile 'com.android.support:support-v13:20.0.0' compile 'com.google.android.gms:play-services:4.4.+' compile ...

Volley的问题和贡献[已关闭](Issues and contribution for Volley [closed])

似乎很多已经在评论中得到了回答,但我会尽力掩盖其余的,或者说,我会尽力涵盖您的具体问题。 1)Volley不会自行处理重定向。 它由底层的HttpStack处理。 例如,我目前使用OkHttp(来自Square)作为我的针对Volley的HTTP客户端。 请参阅https://plus.google.com/108284392618554783657/posts/eJJxhkTQ4yU https://gist.github.com/JakeWharton/5616899 OkHttp非常棒,因为 ...

如何使用Volley获取和解析JSON对象(How to get and parse a JSON-object with Volley)

使用您的Url,您可以使用以下示例代码: RequestQueue requestQueue = Volley.newRequestQueue(this); String url = "https://itunes.apple.com/search?term=michael+jackson"; JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(url, new Response.L ...

Android Volley ImageLoader - 如何使用基本的HTTP授权?(Android Volley ImageLoader - How to use Basic HTTP Authorization?)

我也重写了getHeaders() 。 到目前为止,我还没有找到更容易做到的方法。 请参阅此示例https://github.com/njzk2/VolleyTwitter/blob/master/src/com/njzk2/twitterbrowser/TokenRequest.java重写请求以包含授权标头。 从Volley代码,我没有看到添加自定义标题的任何方式,如果不是通过重写Request对象。 此外,考虑到Volley的结构,我不明白它如何轻松添加,因为Image,ImageReque ...

Android Studio + Volley = NoClassDefFound?(Android Studio + Volley = NoClassDefFound?)

异常java.lang.NoClassDefFoundError:com.google.android.gms.common.AccountPicker 在这里找到修复。 基本上,打开命令提示符(或终端)并导航到您的项目目录。 在Windows上使用以下命令: 对于Windows用户:gradlew.bat干净 对于mac用户输入:./gradlew clean 然后重新加载Android Studio并重试! Exception java.lang.NoClassDefFoundError: c ...

添加ImageLoader时,getInstance(this)中的Android Volley错误(Android Volley error in getInstance(this) when adding ImageLoader)

这是我的工作示例代码。 希望这个帮助: MainActivity.java: import ... public class MainActivity extends Activity { final Context mContext = this; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ...

Google Image by Image API?(Google Search by Image API?)

很抱歉,Google图像API已被弃用 : 重要提示:截至2011年5月26日,Google Image Search API已被正式弃用。它将继续按照我们的弃用政策工作,但每天可能发出的请求数量可能会有限。 肯定有一些选择( http://www.tineye.com/和http://mrisa.mage.me.uk ) 更新(2013):现在Google自定义搜索允许图像搜索。 Sorry to say, but the Google image API is deprecated: Impo ...

相关文章

更多

最新问答

更多
  • Android宽度:100%修复(网站接管问题)(Android width:100% fix (website takeover issue))
  • C ++函数/方法设计的良好实践(Good practice in C++ function/method design)
  • 计算其他表中不存在的所有记录 - SQL查询(Count all records that does not exist to other table - SQL Query)
  • 为什么我要用JPA共享ID?(Why do I get shared Ids with JPA?)
  • asp.net - 如何显示来自html格式的数据行的字段(asp.net - how to display a field from data row that is in html format)
  • 我们如何使用ActiveRecord从连接表中删除行?(How can we delete rows from a join table by using ActiveRecord?)
  • ng-class搞乱了类的顺序(ng-class messing with the order of classes)
  • oracle 12g无效数字错误(oracle 12g invalid number error)
  • 更改ng-src值onclick(Change ng-src value onclick)
  • 如何在android中自动添加自定义依赖项以创建新项目?(How to add custom dependencies automatically in android for ever a new project is created?)
  • datetime函数在PHP中(datetime function in php)
  • 在javascript中获取会话数组的值(in javascript get the value of a session array)
  • 如何在UTF8中编译LaTeX?(How can I compile LaTeX in UTF8? [closed])
  • Rspec:“array.should == another_array”,但不用担心订单(Rspec: “array.should == another_array” but without concern for order)
  • Logcat错误:无法在android片段中加载视图(Logcat error: unable to load view in android fragments)
  • JavaFX的。(JavaFX. Adding items to the list in different threads is not working)
  • 从GDATA日历资源迁移到Google Calendar Resource api(Migrate from GDATA calendar resource to Google Calendar Resource api)
  • SSRS 2008 - 以零情景处理分割(SSRS 2008 - Dealing with division by zero scenarios)
  • 我如何以编程方式添加一个listView列标题的点击事件(How can I add a listView column header a click event programmatically)
  • Wxpython:无法检索有关列表控件项XXX的信息(Wxpython: Couldn't retrieve information about list control item XXX)
  • 使用Tortoise SVN在SVN存储库中移动目录(Move Directory across SVN repository using Tortoise SVN)
  • 天蓝色服务结构集群中的web api无状态服务是否在一段时间不活动后进入休眠状态?(Do web api stateless services in azure service fabric cluster go to sleep after a period of inactivity?)
  • 我可以设置intelliJ来突出显示PHP编码风格吗?(Can I set intelliJ to highlight php coding style?)
  • 用javafx创建一个Truetype字体文件(Creating a Truetype Font file with javafx)
  • Spring ftp配置错误(Spring ftp configuration is wrong)
  • 使用gsub去除多个字符(Using gsub to strip multiple characters)
  • 续订推送证书并保持当前的App Store App正常工作(Renew Push certificate and keep current App Store App working)
  • js:ES5和ES6之间关于'this'关键字用法的一个令人困惑的观点(js: one confusing point about 'this' keyword usage between ES5 and ES6)
  • window.onload vs $(document).ready()(window.onload vs $(document).ready())
  • 在Swift中,如何声明一个符合一个或多个协议的特定类型的变量?(In Swift, how can I declare a variable of a specific type that conforms to one or more protocols?)