–新增許可權
<uses permissionandroid:name="com.android.launcher.permission.READ_SETTINGS" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA" />
–使用相機獲得圖片
–1
private Uri ImageUri=null;
建立一個File物件,用於儲存拍照後的圖片,並把圖片命名為outputImage.jpg,
並把它手機Sd卡的應用快取的位置(就是指Sd卡中專門用於存放當前應用快取資料
的位置,呼叫getExternalCacheDir()方法可以得到這個目錄。)
如果我們使用這種應用快取目錄來存放圖片,就可以跳過執行時許可權的處理,
(Android6.系統開始,讀寫Sd卡被列為了危險許可權,需要進行執行時許可權的處理)。
File outputImage=new File(getExternalCacheDir(),"outputImage.jpg");
try {
if (outputImage.exists()){
outputImage.delete();
}
outputImage.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
這裡進行了一個判斷,如果執行裝置版型低於Android7.0,就呼叫Uri的formFile()方法。
否則,就呼叫FileProvider的getUriForFile()方法將File物件轉為一個封裝過的Uri。
if (Build.VERSION.SDK_INT>=24){
ImageUri= FileProvider.getUriForFile(CallThePolice.this,
"com.example.car.fileprovider",outputImage);
}else {
ImageUri=Uri.fromFile(outputImage);
}
//啟動相機程式
Intent intent=new Intent("android.media.action.IMAGE_CAPTURE");
intent.putExtra(MediaStore.EXTRA_OUTPUT,ImageUri);
startActivityForResult(intent,2);
–2
在AndroidManifest.xml中內容提供器進行註冊。
<provider
android:authorities="com.example.car.fileprovider"
android:name="android.support.v4.content.FileProvider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths"/>
</provider>
其中android:authorities 屬性必須要和剛才FileProvider,getUriForFile()方法的第二個引數一致。另外,
這裡還在<provider>標籤的內部使用<meta-data>來指定Uri的共用路徑,參照一個@xml/file_paths資源。
–3
在res的xml目錄下建立file_path.xml
<?xml version="1.0" encoding="utf-8"?>
<paths>
<external-path name="camera_photos" path="" />
</paths>
其中,external-path就是用來指定Uri共用的,name屬性可以隨便改,path屬性的值表示共用的具體路徑,這裡設空表示將整個卡進行共用。
最後,為了相容Android4.4以下的老版本,在AndroidManifest.xml下宣告,存取Sd卡的許可權。
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
–2呼叫相簿獲得圖片
Intent intent = new Intent();
intent.setType("image/*");//選圖片
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);//選擇多張圖片
intent.setAction(Intent.ACTION_GET_CONTENT);
//Intent.createChooser(),建立應用選擇器,系統會根據條件進行過濾
startActivityForResult(Intent.createChooser(intent, "select_picture"), 1);
–3處理相機和相簿中來的圖片
–1首先建立一個RecyclerView的Adapter
public class PictureAdapter extends RecyclerView.Adapter<PictureAdapter.MyViewHolder> {
private Context mContext;
private List<Bitmap> mDatas;
private LayoutInflater mInflater;
public PictureAdapter(Context context, List<Bitmap> datas, ) {
mContext = context;
mDatas = datas;
mInflater = LayoutInflater.from(context);
}
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = mInflater.inflate(R.layout.load_item_pic, parent, false);
final MyViewHolder holder=new MyViewHolder(itemView);
return holder;
}
@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
Bitmap bitmap= mDatas.get(position);
holder.mIvDisPlayItemPhoto.setImageBitmap(bitmap);
}
@Override
public int getItemCount() {
return mDatas.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
@Bind(R.id.ivPic)
ImageView mIvDisPlayItemPhoto=itemView.findViewById(R.id.ivPic);
public MyViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
}
}
}
–2在onActivityResult中處理相機和相簿中來的資料
private List<Bitmap> bitmap = new ArrayList<>();//用來儲存拍照和相簿中來的圖片
private List<Uri> URI = new ArrayList<>();//用來記錄要上傳照片的路徑,上傳到伺服器要用到
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
int i = 0;
recyclerView = findViewById(R.id.picture);
LinearLayoutManager ms = new LinearLayoutManager(this);
ms.setOrientation(LinearLayoutManager.HORIZONTAL);//將recyclerView的佈局設定為橫向
switch (requestCode) {
case 1://處理相簿返回的資料
if (data != null) {
for (i = 0; i < data.getClipData().getItemCount(),i++) {
URI.add(data.getClipData().getItemAt(i).getUri());
try {
bitmap.add(BitmapFactory.decodeStream(getContentResolver().openInputStream(data.getClipData().getItemAt(i).getUri()), null, null));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
pictureAdapter = new PictureAdapter(getApplicationContext(), bitmap);
recyclerView.setLayoutManager(ms);
recyclerView.setAdapter(pictureAdapter);
} else {
Toast.makeText(CallThePolice.this,"您未選擇圖片",Toast.LENGTH_SHORT).show();
}
break;
case 2://處理相機返回的資料
if(ImageUri==null){
Toast.makeText(CallThePolice.this,"您未選擇圖片",Toast.LENGTH_SHORT).show();
} else{
try {
URI.add(ImageUri);
bitmap.add(BitmapFactory.decodeStream(getContentResolver().openInputStream(ImageUri)));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
pictureAdapter = new PictureAdapter(getApplicationContext(), bitmap);
recyclerView.setLayoutManager(ms);
recyclerView.setAdapter(pictureAdapter);
}
break;
}
}
–4將圖片上傳到伺服器
–1先將圖片的Uri轉為真實路徑
public String getRealPathFromURI(Uri contentUri) {
String res = null;
String[] proj = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(contentUri, proj, null, null, null);
if(cursor.moveToFirst()){;
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
res = cursor.getString(column_index);
}
cursor.close();
return res;
}
–2上傳到伺服器(用Okhttp)
public void Upload() {
MultipartBody.Builder builder=new MultipartBody.Builder();
OkHttpClient okHttpClient=new OkHttpClient();
if(URI!=null && URI.size()!=0){
for(Uri uri:URI){
File file=new File(getRealPathFromURI(uri));
builder.addFormDataPart("file",file.getName(),RequestBody.create(MediaType.parse("image/jpg"),file));
}
MultipartBody multipartBody=builder.build();
final Request request=new Request.Builder()
.url( "http://192.168.123.129:8080/ServerForAndroid/Upload")
.post(multipartBody)
.build();
okHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(@NotNull Call call, @NotNull IOException e) {
if(e.getCause().equals(SocketTimeoutException.class))//如果超時
{
progressBar.setVisibility(View.INVISIBLE);
// Toast.makeText(CallThePolice.this,"上傳失敗",Toast.LENGTH_SHORT).show();
}else{
progressBar.setVisibility(View.INVISIBLE);
Looper.prepare();
Toast.makeText(CallThePolice.this,"上傳失敗",Toast.LENGTH_SHORT).show();
Looper.loop();
}
}
@Override
public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
progressBar.setVisibility(View.INVISIBLE);
Looper.prepare();
Toast.makeText(CallThePolice.this,"上傳成功",Toast.LENGTH_SHORT).show();
Looper.loop();
}
});
}
}
–5伺服器servlet處理邏輯
–1將必要的jar包
這兩個包必須要匯入!(可以用maven下這兩個包)
–2程式碼
package service;
import java.util.ArrayList;
import java.util.List;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class Upload extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
DiskFileItemFactory factory=new DiskFileItemFactory();
System.out.print("in");
String path="D:\\test";
factory.setRepository(new File(path));
factory.setSizeThreshold(1024*1024*4);
ServletFileUpload upload=new ServletFileUpload(factory);
try {
List<FileItem> list=(ArrayList<FileItem>)upload.parseRequest(request);
for(FileItem item:list){
if(!item.isFormField()){
String value = item.getName();
//取到最後一個反斜槓。
int start = value.lastIndexOf("\\");
//擷取上傳檔案的 字串名字。+1是去掉反斜槓。
String filename = value.substring(start+1);
PrintWriter out=response.getWriter();
out.format("sj", "成功");
/*直接寫到檔案中。 */
item.write(new File(path,filename));
}
}
} catch (FileUploadException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.print(e.toString());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.print(e.toString());
}
}
}
–3圖片顯示
如果上傳成功的話,會在D槽的test目錄下,顯示圖片。