import android.graphics.Bitmap; import android.util.Log; import java.io.BufferedOutputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.Iterator; import java.util.Map; import java.util.UUID; /** * Created by on 2018/5/31. */ public class UploadUtil { private static UploadUtil uploadUtil; private static final String BOUNDARY = UUID.randomUUID().toString(); // 边界标识 随机生成 private static final String PREFIX = "--"; private static final String LINE_END = "\r\n"; private static final String CONTENT_TYPE = "multipart/form-data"; // 内容类型 private UploadUtil() { } /** * 单例模式获取上传工具类 * * @return */ public static UploadUtil getInstance() { if (null == uploadUtil) { uploadUtil = new UploadUtil(); } return uploadUtil; } private static final String TAG = "UploadUtil"; private int readTimeOut = 10 * 1000; // 读取超时 private int connectTimeout = 10 * 1000; // 超时时间 /*** * 请求使用多长时间 */ private static int requestTime = 0; private static final String CHARSET = "utf-8"; // 设置编码 /*** * 上传成功 */ public static final int UPLOAD_SUCCESS_CODE = 1; /** * 文件不存在 */ public static final int UPLOAD_FILE_NOT_EXISTS_CODE = 2; /** * 服务器出错 */ public static final int UPLOAD_SERVER_ERROR_CODE = 3; protected static final int WHAT_TO_UPLOAD = 1; protected static final int WHAT_UPLOAD_DONE = 2; /** * android上传文件到服务器 * * @param filePath 需要上传的文件的路径 * @param fileKey 在网页上<input type=file name=xxx/> xxx就是这里的fileKey * @param RequestURL 请求的URL */ public void uploadFile(String filePath, String fileKey, String RequestURL, Map<String, String> param) { if (filePath == null) { sendMessage(UPLOAD_FILE_NOT_EXISTS_CODE, "文件不存在"); return; } try { File file = new File(filePath); uploadFile(file, fileKey, RequestURL, param); } catch (Exception e) { sendMessage(UPLOAD_FILE_NOT_EXISTS_CODE, "文件不存在"); e.printStackTrace(); return; } } /** * android上传文件到服务器 * * @param file 需要上传的文件 * @param fileKey 在网页上<input type=file name=xxx/> xxx就是这里的fileKey * @param RequestURL 请求的URL */ public void uploadFile(final File file, final String fileKey, final String RequestURL, final Map<String, String> param) { if (file == null || (!file.exists())) { sendMessage(UPLOAD_FILE_NOT_EXISTS_CODE, "文件不存在"); return; } Log.i(TAG, "请求的URL=" + RequestURL); Log.i(TAG, "请求的fileName=" + file.getName()); Log.i(TAG, "请求的fileKey=" + fileKey); new Thread(new Runnable() { //开启线程上传文件 @Override public void run() { toUploadFile(file, fileKey, RequestURL, param); } }).start(); } private void toUploadFile(File file, String fileKey, String RequestURL, Map<String, String> param) { String result = null; requestTime = 0; long requestTime = System.currentTimeMillis(); long responseTime = 0; try { URL url = new URL(RequestURL); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(readTimeOut); conn.setConnectTimeout(connectTimeout); conn.setDoInput(true); // 允许输入流 conn.setDoOutput(true); // 允许输出流 conn.setUseCaches(false); // 不允许使用缓存 conn.setRequestMethod("POST"); // 请求方式 conn.setRequestProperty("Charset", CHARSET); // 设置编码 conn.setRequestProperty("connection", "keep-alive"); conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)"); conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY); // conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); /** * 当文件不为空,把文件包装并且上传 */ DataOutputStream dos = new DataOutputStream(conn.getOutputStream()); StringBuffer sb = null; 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 = null; params = null; sb = new StringBuffer(); /** * 这里重点注意: name里面的值为服务器端需要key 只有这个key 才可以得到对应的文件 * filename是文件的名字,包含后缀名的 比如:abc.png */ sb.append(PREFIX).append(BOUNDARY).append(LINE_END); sb.append("Content-Disposition:form-data; name=\"" + fileKey + "\"; filename=\"" + file.getName() + "\"" + LINE_END); sb.append("Content-Type:image/pjpeg" + LINE_END); // 这里配置的Content-type很重要的 ,用于服务器端辨别文件的类型的 sb.append(LINE_END); params = sb.toString(); sb = null; Log.i(TAG, file.getName() + "=" + params + "##"); dos.write(params.getBytes()); /**上传文件*/ InputStream is = new FileInputStream(file); onUploadProcessListener.initUpload((int) file.length()); byte[] bytes = new byte[1024]; int len = 0; int curLen = 0; while ((len = is.read(bytes)) != -1) { curLen += len; dos.write(bytes, 0, len); onUploadProcessListener.onUploadProcess(curLen); } is.close(); dos.write(LINE_END.getBytes()); byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINE_END).getBytes(); dos.write(end_data); dos.flush(); // // dos.write(tempOutputStream.toByteArray()); /** * 获取响应码 200=成功 当响应成功,获取响应的流 */ int res = conn.getResponseCode(); responseTime = System.currentTimeMillis(); this.requestTime = (int) ((responseTime - requestTime) / 1000); Log.e(TAG, "response code:" + res); if (res == 200) { Log.e(TAG, "request success"); InputStream input = conn.getInputStream(); StringBuffer sb1 = new StringBuffer(); int ss; while ((ss = input.read()) != -1) { sb1.append((char) ss); } result = sb1.toString(); Log.e(TAG, "result : " + result); sendMessage(UPLOAD_SUCCESS_CODE, "上传结果:" + result); return; } else { Log.e(TAG, "request error" + res); sendMessage(UPLOAD_SERVER_ERROR_CODE, "上传失败:code=" + res); return; } } catch (MalformedURLException e) { sendMessage(UPLOAD_SERVER_ERROR_CODE, "上传失败:error=" + e.getMessage()); e.printStackTrace(); return; } catch (IOException e) { sendMessage(UPLOAD_SERVER_ERROR_CODE, "上传失败:error=" + e.getMessage()); e.printStackTrace(); return; } } /** * 发送上传结果 * * @param responseCode * @param responseMessage */ private void sendMessage(int responseCode, String responseMessage) { onUploadProcessListener.onUploadDone(responseCode, responseMessage); } /** * 下面是一个自定义的回调函数,用到回调上传文件是否完成 * * @author shimingzheng */ public static interface OnUploadProcessListener { /** * 上传响应 * * @param responseCode * @param message */ void onUploadDone(int responseCode, String message); /** * 上传中 * * @param uploadSize */ void onUploadProcess(int uploadSize); /** * 准备上传 * * @param fileSize */ void initUpload(int fileSize); } private OnUploadProcessListener onUploadProcessListener; public void setOnUploadProcessListener( OnUploadProcessListener onUploadProcessListener) { this.onUploadProcessListener = onUploadProcessListener; } public int getReadTimeOut() { return readTimeOut; } public void setReadTimeOut(int readTimeOut) { this.readTimeOut = readTimeOut; } public int getConnectTimeout() { return connectTimeout; } public void setConnectTimeout(int connectTimeout) { this.connectTimeout = connectTimeout; } /** * 获取上传使用的时间 * * @return */ public static int getRequestTime() { return requestTime; } public static interface uploadProcessListener { } /** * 将Bitmap转换成文件 * 保存文件 * * @param bm * @param fileName * @throws IOException */ public static File saveFile(Bitmap bm, String path, String fileName) throws IOException { File dirFile = new File(path); if (!dirFile.exists()) { dirFile.mkdir(); } File myCaptureFile = new File(path, fileName); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile)); bm.compress(Bitmap.CompressFormat.JPEG, 80, bos); bos.flush(); bos.close(); return myCaptureFile; } }
import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Bitmap; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.os.Message; import android.provider.MediaStore; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.Toast; import com.bawei.moni31.R; import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.Map; import okhttp3.Call; import okhttp3.Callback; import okhttp3.MediaType; import okhttp3.MultipartBody; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; /** * Created by on 2018/6/1. */ public class Fragmenttouxiang extends Fragment implements UploadUtil.OnUploadProcessListener{ private ImageView mImageView; private static final int PHOTO_REQUEST = 1; private static final int CAMERA_REQUEST = 2; private static final int PHOTO_CLIP = 3; private static final int UPLOAD_INIT_PROCESS = 4;//上传初始化 protected static final int UPLOAD_FILE_DONE = 2;//上传中 private static final int UPLOAD_IN_PROCESS = 5;//上传文件响应 private ProgressDialog pd; private File filepath;//返回的文件地址 View inflate; private String set="https://www.zhaoapi.cn/file/upload?uid=13681"; @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { inflate= inflater.inflate(R.layout.layout_touxiang, container, false); mImageView = (ImageView) inflate.findViewById(R.id.imageView); mImageView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { AlertDialog builder = new AlertDialog.Builder(getActivity()) .setTitle("选择头像") .setPositiveButton("相机", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { getCamera(); } }) .setNegativeButton("相册", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { getPhoto(); } }) .show(); } }); return inflate; } private void getPhoto() { Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*"); startActivityForResult(intent, PHOTO_REQUEST); } private void getCamera() { Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); // 下面这句指定调用相机拍照后的照片存储的路径 intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File( Environment.getExternalStorageDirectory(), "hand.jpg"))); startActivityForResult(intent, CAMERA_REQUEST); } private void photoClip(Uri uri) { // 调用系统中自带的图片剪裁 Intent intent = new Intent("com.android.camera.action.CROP"); intent.setDataAndType(uri, "image/*"); // 下面这个crop=true是设置在开启的Intent中设置显示的VIEW可裁剪 intent.putExtra("crop", "true"); // aspectX aspectY 是宽高的比例 intent.putExtra("aspectX", 1); intent.putExtra("aspectY", 1); // outputX outputY 是裁剪图片宽高 intent.putExtra("outputX", 150); intent.putExtra("outputY", 150); intent.putExtra("return-data", true); startActivityForResult(intent, PHOTO_CLIP); } private void toUploadFile() { pd = ProgressDialog.show(getActivity(), "", "正在上传文件..."); pd.show(); String fileKey = "avatarFile"; UploadUtil uploadUtil = UploadUtil.getInstance(); uploadUtil.setOnUploadProcessListener(this); //设置监听器监听上传状态 Map<String, String> params = new HashMap<String, String>();//上传map对象 params.put("userId", ""); uploadUtil.uploadFile(filepath, fileKey, "上传头像的地址", params); Toast.makeText(getActivity(), "上传成功", Toast.LENGTH_LONG).show(); } @Override public void onUploadDone(int responseCode, String message) { pd.dismiss(); Message msg = Message.obtain(); msg.what = UPLOAD_FILE_DONE; msg.arg1 = responseCode; msg.obj = message; } @Override public void onUploadProcess(int uploadSize) { //上传中 Message msg = Message.obtain(); msg.what = UPLOAD_IN_PROCESS; msg.arg1 = uploadSize; } @Override public void initUpload(int fileSize) { //准备上传 Message msg = Message.obtain(); msg.what = UPLOAD_INIT_PROCESS; msg.arg1 = fileSize; } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); switch (requestCode) { case CAMERA_REQUEST: switch (resultCode) { case -1://-1表示拍照成功 File file = new File(Environment.getExternalStorageDirectory() + "/hand.jpg");//保存图片 if (file.exists()) { //对相机拍照照片进行裁剪 photoClip(Uri.fromFile(file)); } } break; case PHOTO_REQUEST://从相册取 if (data != null) { Uri uri = data.getData(); //对相册取出照片进行裁剪 photoClip(uri); } break; case PHOTO_CLIP: //完成 if (data != null) { Bundle extras = data.getExtras(); if (extras != null) { Bitmap photo = extras.getParcelable("data"); try { //获得图片路径 filepath = UploadUtil.saveFile(photo, Environment.getExternalStorageDirectory().toString(), "hand.jpg"); //上传照片 toUploadFile(); } catch (IOException e) { e.printStackTrace(); } //上传完成将照片写入imageview与用户进行交互 mImageView.setImageBitmap(photo); uploadPic(set,filepath,"hand.jpg"); } } break; } } public static void uploadPic(String url, File file, String fileName) { //创建OkHttpClient请求对象 OkHttpClient okHttpClient = new OkHttpClient(); //创建RequestBody 封装file参数 RequestBody fileBody = RequestBody.create(MediaType.parse("application/octet-stream"), file); //创建RequestBody 设置类型等 RequestBody requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM).addFormDataPart("file", fileName, fileBody).build(); //创建Request Request request = new Request.Builder().url(url).post(requestBody).build(); //得到Call Call call = okHttpClient.newCall(request); //执行请求 call.enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { Log.d("失败", "onResponse: 很不高兴"); } @Override public void onResponse(Call call, Response response) throws IOException { //上传成功回调 目前不需要处理 Log.d("成功", "onResponse: 开心"); } }); } }
compile 'com.squareup.okhttp3:okhttp:3.4.1' compile 'com.squareup.okio:okio:1.5.0' compile 'com.google.code.gson:gson:2.2.4'