方法一、利用OKhttp上传图片
/**
* 利用OKhttp上传图片
*/
private void UpLoadPicture() {
//判断文件夹中是否有文件存在
File file = new File(getExternalCacheDir(),"output_image.jpg");
if (!file.exists()){
Toast.makeText(getApplicationContext(),"文件不存在",Toast.LENGTH_SHORT).show();
return;
}
OkHttpClient client = new OkHttpClient();
//String imgPath = getExternalCacheDir().getPath() + "/output_image.jpg";
MultipartBody.Builder builder = new MultipartBody.Builder();
builder.addFormDataPart("file",imgPath, RequestBody.create(MediaType.parse("image/jpg"),new File(imgPath)));
RequestBody requestBody = builder.build();
Request.Builder reqBuilder = new Request.Builder();
Request request = reqBuilder
.url("http://192.168.201.211:8000/yks/file/server/")
.post(requestBody)
.build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
runOnUiThread(new Runnable() {
@Override
public void run() {
// aBuilder.dismiss();
Toast.makeText(getApplicationContext(),"上传失败",Toast.LENGTH_SHORT).show();
}
});
}
@Override
public void onResponse(Call call, Response response) throws IOException {
final String resp = response.body().toString();
runOnUiThread(new Runnable() {
@Override
public void run() {
// aBuilder.dismiss();
Toast.makeText(getApplicationContext(),resp,Toast.LENGTH_SHORT).show();
}
});
}
});
}
方法二、newpda
/**
* 上传图片到服务器
* @param path
*/
public final void upLoadFile(String path) {
new FileUpLoadManager().upLoadFile(path, new FileUpLoadManager.FileUpLoadCallBack() {
@Override
public void onError(Throwable e) {
//Toast.makeText(,"上传失败,请稍后重试",Toast.LENGTH_LONG).show();
}
@Override
public void onSuccess(String url) {
Log.e("图片上传成功",url);
// Toast.makeText(AddProductActivity.this,url, Toast.LENGTH_LONG).show();
// upload.setText("已上传");
// upload.setBackgroundColor(Color.parseColor("#32cd32"));
// upload.setClickable(false);
}
@Override
public void onProgress(int pro) {
}
});
}
package com.example.baseactivity;
import android.util.Log;
import com.google.gson.Gson;
import java.io.File;
import java.util.concurrent.TimeUnit;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSession;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public class FileUpLoadManager {
private String FileType_Image = "image";
private String FileType_Video = "video";
public interface FileUpLoadCallBack {
void onError(Throwable e);
void onSuccess(String url);
void onProgress(int pro);
}
public interface FileDownloadCallBack {
void onError(Throwable e);
void onSuccess(String url);
}
// private String UPLOAD_URL = "http://192.168.1.127:8082/uploadFile";
private String UPLOAD_URL = "http://10.90.1.204:8000/yks/file/server/";
public OkHttpClient getHttpClient() {
return new OkHttpClient.Builder()
.hostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
})
.connectTimeout(1000L * 60 * 3, TimeUnit.MILLISECONDS)
.readTimeout(1000L * 60 * 3, TimeUnit.MILLISECONDS)
.build();
}
public void upLoadFile(String path, final FileUpLoadCallBack callBack) {
MultipartBody.Builder muBuilder = new MultipartBody.Builder();
muBuilder.setType(MultipartBody.FORM);
File file = new File(path);
if (path.endsWith(".PNG") || path.endsWith(".png") ||
path.endsWith(".JPG") || path.endsWith(".jpg") ||
path.endsWith(".JPEG") || path.endsWith(".jpeg")) {
RequestBody fileBody = RequestBody.create(MediaType.parse("image/jpg"), file);
ProgressRequestBody requestBody = new ProgressRequestBody(fileBody, new ProgressRequestListener() {
@Override
public void onRequestProgress(int pro, long contentLength, boolean done) {
Log.d("TAG", "pro=====" + pro );
if (callBack != null) {
callBack.onProgress(pro);
}
}
});
muBuilder.addFormDataPart(FileType_Image, file.getName(), requestBody);
} else if (path.endsWith(".rm") || path.endsWith(".rmvb") ||
path.endsWith(".mpeg1-4") || path.endsWith(".mov") ||
path.endsWith(".dat") || path.endsWith(".wmv") ||
path.endsWith(".avi") || path.endsWith(".3gp") ||
path.endsWith(".amv") || path.endsWith(".dmv") ||
path.endsWith(".flv") || path.endsWith(".mp3")||path.endsWith(".amr")) {
RequestBody fileBody = RequestBody.create(MediaType.parse("application/octet-stream"), file);
ProgressRequestBody requestBody = new ProgressRequestBody(fileBody, new ProgressRequestListener() {
@Override
public void onRequestProgress(int pro, long contentLength, boolean done) {
Log.d("TAG", "pro=====" + pro + "--------position-------");
if (callBack != null) {
callBack.onProgress(pro);
}
}
});
muBuilder.addFormDataPart(FileType_Video, file.getName(), requestBody);
}
Log.d("TAG", "参数设置完毕");
sendRequest(muBuilder.build(), callBack);
}
private void sendRequest(MultipartBody build, FileUpLoadCallBack callBack) {
final Request request = new Request.Builder().url(UPLOAD_URL).post(build).build();
Observable.create(new ObservableOnSubscribe<String>() {
@Override
public void subscribe(ObservableEmitter<String> emitter) throws Exception {
Response response = getHttpClient().newCall(request).execute();
if (response.isSuccessful()) {
String json = response.body().string();
Log.e("TAG", "====body1111111111========" + json);
try {
UpLoadFileBean bean = new Gson().fromJson(json, UpLoadFileBean.class);
if (bean.getState().equals("000001")) {
Log.e("TAG111", "====bod==" + json);
emitter.onNext(bean.getData());
}
}catch (Exception e){
e.printStackTrace();
}
} else {
emitter.onError(new IllegalStateException(response.message()));
}
}
}).subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(getObserver(callBack));
}
private Observer<String> getObserver(final FileUpLoadCallBack callBack) {
Observer<String> observer = new Observer<String>() {
@Override
public void onSubscribe(Disposable d) {
}
@Override
public void onNext(String strings) {
if (callBack != null) {
callBack.onSuccess(strings);
}
}
@Override
public void onError(Throwable e) {
if (callBack != null) {
callBack.onError(e);
}
}
@Override
public void onComplete() {
}
};
return observer;
}
private Observer<String> getObserverDownload(final FileDownloadCallBack callBack) {
Observer<String> observer = new Observer<String>() {
@Override
public void onSubscribe(Disposable d) {
}
@Override
public void onNext(String strings) {
if (callBack != null) {
callBack.onSuccess(strings);
}
}
@Override
public void onError(Throwable e) {
if (callBack != null) {
callBack.onError(e);
}
}
@Override
public void onComplete() {
}
};
return observer;
}
/* public void downloadFile(String url, final String fileName, final FileDownloadCallBack callBack){
final Request request = new Request.Builder()
.url(url)
.build();
Observable.create(new ObservableOnSubscribe<String>() {
@Override
public void subscribe(ObservableEmitter<String> emitter) throws Exception {
Response response = getHttpClient().newCall(request).execute();
if (response.isSuccessful()) {
InputStream is = null;
byte[] buf = new byte[2048];
int len = 0;
FileOutputStream fos = null;
//储存下载文件的目录
File dir = new File(CBVoice.DEF_FILEPATH);
if (!dir.exists()) {
dir.mkdirs();
}
File file = new File(dir,fileName);
try {
is = response.body().byteStream();
long total = response.body().contentLength();
fos = new FileOutputStream(file);
long sum = 0;
while ((len = is.read(buf)) != -1) {
fos.write(buf, 0, len);
sum += len;
int progress = (int) (sum * 1.0f / total * 100);
//下载中更新进度条
}
fos.flush();
//下载完成
callBack.onSuccess(file.getAbsolutePath());
}catch (Exception e){
callBack.onError(e);
}finally {
try {
if (is != null) {
is.close();
}
if (fos != null) {
fos.close();
}
} catch (IOException e) {
}
}
} else {
emitter.onError(new IllegalStateException(response.message()));
}
}
}).subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(getObserverDownload(callBack));
}*/
public static Boolean whereExists(String filePath){
if (filePath.isEmpty()){return false;}
File file = new File(filePath);
return file.exists() ? true: false;
}
}
方法三、
/**
* android上传文件到服务器
* @param file 需要上传的文件
* @param // RequestURL 请求的rul
* @return 返回响应的内容
*/
public void uploadFile(File file, Map<String, String> param){
// Android 4.0 之后不能在主线程中请求HTTP请求
new Thread(new Runnable(){
@Override
public void run() {
String RequestUrl="http://192.168.201.211:8000/yks/file/server/";
String result = null;
String BOUNDARY = UUID.randomUUID().toString(); //边界标识 随机生成
String PREFIX = "--" , LINE_END = "\r\n";
String CONTENT_TYPE = "multipart/form-data"; //内容类型
// 显示进度框
//showProgressDialog();
try {
URL url = new URL(RequestUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(20000);
conn.setConnectTimeout(20000);
conn.setDoInput(true); //允许输入流
conn.setDoOutput(true); //允许输出流
conn.setUseCaches(false); //不允许使用缓存
conn.setRequestMethod("POST"); //请求方式
// conn.setRequestProperty("Charset", CHARSET); //设置编码
// conn.setRequestProperty("connection", "keep-alive");
// conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY)
;
if(file!=null){
/**
* 当文件不为空,把文件包装并且上传
*/
DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
StringBuffer sb = new StringBuffer();
String params = "";
if (param != null && param.size() > 0) {
Iterator<String> it = param.keySet().iterator();
while (it.hasNext()) {
sb = null;
sb = new StringBuffer();
String key = it.next();
String value = param.get(key);
sb.append(PREFIX).append(BOUNDARY).append(LINE_END);
sb.append("Content-Disposition: form-data; name=\"").append(key).append("\"").append(LINE_END).append(LINE_END);
sb.append(value).append(LINE_END);
params = sb.toString();
Log.i(TAG, key+"="+params+"##");
dos.write(params.getBytes());
// dos.flush();
}
}
sb = new StringBuffer();
sb.append(PREFIX);
sb.append(BOUNDARY);
sb.append(LINE_END);
/**
* 这里重点注意:
* name里面的值为服务器端需要key 只有这个key 才可以得到对应的文件
* filename是文件的名字,包含后缀名的 比如:abc.png
*/
sb.append("Content-Disposition: form-data; name=\"upfile\";filename=\""+file.getName()+"\""+LINE_END);
sb.append("Content-Type: image/pjpeg; charset="+CHARSET+LINE_END);
sb.append(LINE_END);
dos.write(sb.toString().getBytes());
InputStream is = new FileInputStream(file);
byte[] bytes = new byte[1024];
int len = 0;
while((len=is.read(bytes))!=-1){
dos.write(bytes, 0, len);
}
is.close();
dos.write(LINE_END.getBytes());
byte[] end_data = (PREFIX+BOUNDARY+PREFIX+LINE_END).getBytes();
dos.write(end_data);
dos.flush();
/**
* 获取响应码 200=成功
* 当响应成功,获取响应的流
*/
int res = conn.getResponseCode();
System.out.println("res========="+res);
if(res==200){
Log.e("hhhhhhh","成功成功成功成功成功成功成功成功成功成功成功成功成功成功成功成功成功成功");
ToastUtils.show("成功成功成功成功成功成功成功成功成功成功成功成功成功成功成功成功成功成功");
InputStream input = conn.getInputStream();
StringBuffer sb1= new StringBuffer();
int ss ;
while((ss=input.read())!=-1){
sb1.append((char)ss);
}
result = sb1.toString();
// // 移除进度框
// removeProgressDialog();
// finish();
}
else{
Log.e("hhhhhhh","请求失败");
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// Log.e("hhhhhhh",result);
// ToastUtils.show(result);
// return result;
}
}).start();
}
方法四:
public void img(File file){
OkHttpUtils.post().url("http://10.90.1.204:8000/yks/file/server/")
.addFile("file",System.currentTimeMillis()+".jpg",file)
.tag(this)
.build()
.connTimeOut(20000)
.readTimeOut(20000)
.execute(new StringCallback() {
@Override
public void onError(Call call, Exception e, int id) {
ToastUtils.show(e.getMessage());
}
@Override
public void onResponse(String response, int id) {
try {
JSONObject object = new JSONObject(response);
String state = object.getString("state");
String msg = object.getString("msg");
ToastUtils.show(msg);
} catch (JSONException e) {
e.printStackTrace();
ToastUtils.show(e.getMessage());
}
}
});
}
方法五:
/**
* post请求
*/
public void uploadImage(File file) {
List<File> fileList=new ArrayList<>();
fileList.add(file);
EasyHttp.post("http://10.90.1.204:8000/yks/file/server/")
// .addHeader("group","rpc-service-group-test")
.addFileParams("file", fileList, new ProgressResponseCallBack() {
@Override
public void onResponseProgress(long bytesWritten, long contentLength, boolean done) {
}
})
.accessToken(true)
.timeStamp(true)
.execute(new SimpleCallBack<String>() {
@Override
public void onError(ApiException e) {
ToastUtils.show(e.getMessage());
}
@Override
public void onSuccess(String response) {
ToastUtils.show(response);
}
});
}