1.導(dǎo)依賴
//okhttp
implementation 'com.squareup.okhttp3:okhttp:3.11.0'
//butterknife
implementation 'com.jakewharton:butterknife:8.8.1'
annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1'
//glide
implementation 'com.github.bumptech.glide:glide:4.8.0'
annotationProcessor 'com.github.bumptech.glide:compiler:4.8.0'
//gson
implementation 'com.google.code.gson:gson:2.2.4'
implementation 'com.squareup.retrofit2:retrofit:2.4.0'
implementation 'com.squareup.retrofit2:converter-gson:2.4.0' // 必要依賴嗦玖,解析json字符所用
implementation 'com.squareup.retrofit2:adapter-rxjava2:2.4.0' // 必要依賴又谋,和Rxjava結(jié)合必須用到,下面會(huì)提到
implementation "io.reactivex.rxjava2:rxjava:2.1.3" // 必要rxjava2依賴
implementation "io.reactivex.rxjava2:rxandroid:2.0.1" // 必要rxandrroid依賴墨辛,切線程時(shí)需要用到
2.OK上傳
private void okHttpUpload() {
//上傳一個(gè)sd卡圖片,處理權(quán)限
//注意文件位置
File file = new File("/storage/emulated/legacy/Pictures/g.png");
//ok 網(wǎng)絡(luò)請(qǐng)求, okhttpclinet.newCall().enqueue()
//提交文件的請(qǐng)求,里面含文件
MediaType parse = MediaType.parse("application/octet-stream");
RequestBody fileBody = RequestBody.create(parse, file);
//分塊請(qǐng)求的請(qǐng)求體
RequestBody body = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("key", "857")//指定服務(wù)器保存圖片的文件夾
.addFormDataPart("file", file.getName(), fileBody)//上傳的文件
.build();
Request request = new Request.Builder()
.url(mUrl)
.post(body)
.build();
mOkHttpClient.newCall(request)
.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.d(TAG, "onFailure: " + e.toString());
}
@Override
public void onResponse(Call call, Response response) throws IOException {
Log.d(TAG, "onResponse: " + response.body().string());
}
});
}
3.Retrofit上傳
//底層是ok
private void retrofitUpload() {
File file = new File("/storage/emulated/legacy/Pictures/o.jpg");
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
MediaType parse = MediaType.parse("application/octet-stream");
RequestBody requestBody = MultipartBody.create(parse, file);
MultipartBody.Part part = MultipartBody.Part.createFormData("file", file.getName(), requestBody);
new Retrofit.Builder()
.baseUrl(ApiService.url_up)
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build()
.create(ApiService.class)
.getUp(part)
.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
try {
String string = response.body().string();
Log.e(TAG, "onResponse: " + string);
String[] split = string.split("<br />");
String s = split[split.length - 1];
UpBean upBean = new Gson().fromJson(s, UpBean.class);
Glide.with(LoadActivity.this).load(upBean.getData().getUrl()).into(iv);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
}
});
}
4.HttpUrlCollection上傳
HashMap<String, String> map = new HashMap<>();
map.put("key", "666");
File file = new File("/storage/emulated/legacy/Pictures/g.png");
new Thread(new Runnable() {
@Override
public void run() {
uploadForm(null, "file", file, "xxx.jpg", mUrl);
}
}).start();
public void uploadForm(Map<String, String> params, String fileFormName, File uploadFile, String newFileName, String urlStr) {
if (newFileName == null || newFileName.trim().equals("")) {
newFileName = uploadFile.getName();
}
StringBuilder sb = new StringBuilder();
/**
* 普通的表單數(shù)據(jù)
*/
if (params != null) {
for (String key : params.keySet()) {
sb.append("--" + BOUNDARY + "\r\n");
sb.append("Content-Disposition: form-data; name=\"" + key + "\"" + "\r\n");
sb.append("\r\n");
sb.append(params.get(key) + "\r\n");
}
}
try {
/**
* 上傳文件的頭
*/
sb.append("--" + BOUNDARY + "\r\n");
sb.append("Content-Disposition: form-data; name=\"" + fileFormName + "\"; filename=\"" + newFileName + "\""+ "\r\n");
sb.append("Content-Type: application/octet-stream" + "\r\n");// 如果服務(wù)器端有文件類型的校驗(yàn),必須明確指定ContentType
sb.append("\r\n");
byte[] headerInfo = sb.toString().getBytes("UTF-8");
byte[] endInfo = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("UTF-8");
URL url = null;
url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
// 設(shè)置傳輸內(nèi)容的格式,以及長(zhǎng)度
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
conn.setRequestProperty("Content-Length",String.valueOf(headerInfo.length + uploadFile.length() + endInfo.length));
conn.setDoOutput(true);
OutputStream out = conn.getOutputStream();
InputStream in = new FileInputStream(uploadFile);
//寫入的文件長(zhǎng)度
int count = 0;
//文件的總長(zhǎng)度
int available = in.available();
// 寫入頭部 (包含了普通的參數(shù)惫撰,以及文件的標(biāo)示等)
out.write(headerInfo);
// 寫入文件
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) != -1) {
out.write(buf, 0, len);
count += len;
int progress = count * 100 / available;
Log.d(TAG, "上傳進(jìn)度: " + progress + " %");
}
// 寫入尾部
out.write(endInfo);
in.close();
out.close();
if (conn.getResponseCode() == 200) {
System.out.println("文件上傳成功");
String s = stream2String(conn.getInputStream());
Log.d(TAG, "uploadForm: " + s);
}
} catch (Exception e) {
e.printStackTrace();
}
}
5.拍照上傳
//拍照上傳,注意危險(xiǎn)權(quán)限處理
private void takePhoto() {
if (PackageManager.PERMISSION_GRANTED ==
ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA)) {
//有權(quán)限
openCamera();
} else {
//沒有權(quán)限
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.CAMERA}, 200);
}
}
//開啟相機(jī)
private void openCamera() {
//系統(tǒng)所有的界面都是activity,啟動(dòng)activity方式幾種?
//顯示啟動(dòng):指名道姓的啟動(dòng)
//new Intent(this,MainActivity.class)
//隱式啟動(dòng):不指名道姓,匹配的方式,data,category,action,系統(tǒng)的界面一般都是隱式啟動(dòng)
//創(chuàng)建文件用于保存圖片
mFile = new File(getExternalCacheDir(), System.currentTimeMillis() + ".jpg");
if (!mFile.exists()) {
try {
mFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
//適配7.0以上
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
mImageUri = Uri.fromFile(mFile);
} else {
//第二個(gè)參數(shù)要和清單文件中的配置保持一致
//私有目錄訪問受限,需要清單文件配置ContentProvider
//如果不配置,會(huì)報(bào)FileUriExposedException: file:///storage/emulated/0/Android/data/com.xts.upload/cache/1589178590497.jpg
mImageUri = FileProvider.getUriForFile(this, "com.example.upload", mFile);
}
//啟動(dòng)相機(jī)
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, mImageUri);//將拍照?qǐng)D片存入mImageUri
startActivityForResult(intent, CAMERA_CODE);
}
6.相冊(cè)上傳
//開啟相冊(cè)選取圖片上傳
private void album() {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
startActivityForResult(intent, ALBUM_CODE);
}