This article shares the specific code for uploading local pictures to the network for your reference. The specific content is as follows
First of all, Okhttp is used here, so a dependency is needed:
compile '.okhttp3:okhttp:3.9.0'
xml layout
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:andro xmlns:app="/apk/res-auto" xmlns:tools="/tools" android:layout_width="match_parent" android:orientation="vertical" android:layout_height="match_parent" tools:context="."> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:/> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:/> </LinearLayout>
Medium: Permissions
<uses-permission android:name=""/> <uses-permission android:name=".WRITE_EXTERNAL_STORAGE"/> <uses-permission android:name=".READ_EXTERNAL_STORAGE"/>
MainActivity:
oncreat:
@Override protected void onCreate(Bundle savedInstanceState) { (savedInstanceState); setContentView(.activity_main); findViewById().setOnClickListener(new () { @Override public void onClick(View view) { toPhoto(); } }); findViewById().setOnClickListener(new () { @Override public void onClick(View view) { toCamera(); } }); }
Methods that are of the same level as oncreat:
public void postFile(File file){ // sdcard/dliao/ String path = () ; String [] split = ("\\/"); MediaType MEDIA_TYPE_PNG = ("image/png"); OkHttpClient client = new OkHttpClient(); RequestBody requestBody = new () .setType() // file .addFormDataPart("imageFileName",split[-1]) .addFormDataPart("image",split[-1],(MEDIA_TYPE_PNG,file)) .build(); Request request = new ().post(requestBody).url("http://qhb./Bwei/upload").build(); (request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { } @Override public void onResponse(Call call, Response response) throws IOException { ("response = " + ().string()); } }); } static final int INTENTFORCAMERA = 1 ; static final int INTENTFORPHOTO = 2 ; public String LocalPhotoName; public String createLocalPhotoName() { LocalPhotoName = () + ""; return LocalPhotoName ; } public void toCamera(){ try { Intent intentNow = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); Uri uri = null ; // if (.SDK_INT >= Build.VERSION_CODES.N) { //For Android 7.0, the path encapsulated through FileProvider needs to be provided to external calls// uri = (, "", (createLocalPhotoName()));// Create a content-type Uri through FileProvider and encapsulate it// }else { uri = ((createLocalPhotoName())) ; // } (MediaStore.EXTRA_OUTPUT, uri); startActivityForResult(intentNow, INTENTFORCAMERA); } catch (Exception e) { (); } } /** * Open the album */ public void toPhoto(){ try { createLocalPhotoName(); Intent getAlbum = new Intent(Intent.ACTION_GET_CONTENT); ("image/*"); startActivityForResult(getAlbum, INTENTFORPHOTO); } catch (Exception e) { (); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { (requestCode, resultCode, data); switch (requestCode) { case INTENTFORPHOTO: //Photo album try { // This must be done, otherwise there will be problems on the 4.4.2 mobile phone Uri originalUri = (); File f = null; if (originalUri != null) { f = new File(, LocalPhotoName); String[] proj = {}; Cursor actualimagecursor = ().query(originalUri, proj, null, null, null); if (null == actualimagecursor) { if (().startsWith("file:")) { File file = new File(().substring(7, ().length())); if(!()){ //The address contains the Chinese coded address for utf-8 encoding originalUri = (((),"UTF-8")); file = new File(().substring(7, ().length())); } FileInputStream inputStream = new FileInputStream(file); FileOutputStream outputStream = new FileOutputStream(f); copyStream(inputStream, outputStream); } } else { // System Gallery int actual_image_column_index = (); (); String img_path = (actual_image_column_index); if (img_path == null) { InputStream inputStream = ().openInputStream(originalUri); FileOutputStream outputStream = new FileOutputStream(f); copyStream(inputStream, outputStream); } else { File file = new File(img_path); FileInputStream inputStream = new FileInputStream(file); FileOutputStream outputStream = new FileOutputStream(f); copyStream(inputStream, outputStream); } } Bitmap bitmap = ((), 1080); int width = (); int height = (); FileOutputStream fos = new FileOutputStream(()); if (bitmap != null) { if ((, 85, fos)) { (); (); } if (!()) { (); } ("f = " + ()); postFile(f); } } } catch (Exception e) { (); } break; case INTENTFORCAMERA: // camera try { //file is the original photo I got after taking the photo File file = new File(, LocalPhotoName); Bitmap bitmap = ((), 1080); int width = (); int height = (); FileOutputStream fos = new FileOutputStream(()); if (bitmap != null) { if ((, 85, fos)) { (); (); } if (!()) { //Notification system Recycling bitmap (); } ("f = " + ()); postFile(file); } } catch (Exception e) { (); } break; } } public static void copyStream(InputStream inputStream, OutputStream outStream) throws Exception { try { byte[] buffer = new byte[1024]; int len = 0; while ((len = (buffer)) != -1) { (buffer, 0, len); } (); } catch (IOException e) { (); }finally { if(inputStream != null){ (); } if(outStream != null){ (); } } }
ImageResizeUtils:
package .czx10; import ; import ; import ; import ; import ; import ; import ; import ; import ; import ; import static ; /** * Created by czx on 2017/9/27. */ public class ImageResizeUtils { /** * Photo path * Compressed width dimensions * @param path * @param specifiedWidth */ public static Bitmap resizeImage(String path, int specifiedWidth) throws Exception { Bitmap bitmap = null; FileInputStream inStream = null; File f = new File(path); (path); if (!()) { throw new FileNotFoundException(); } try { inStream = new FileInputStream(f); int degree = readPictureDegree(path); opt = new (); //Photoes are not loaded into memory and can only read photo border information. = true; // Get the width and height of this picture decodeFile(path, opt); // Return bm is empty at this time int inSampleSize = 1; final int width = ; // width The original width of the photo specifiedWidth width required for compression// 1000 980 if (width > specifiedWidth) { inSampleSize = (int) (width / (float) specifiedWidth); } // Sample according to 565. One pixel takes up 2 bytes = .RGB_565; // Pictures are loaded into memory = false; // Equal sampling = inSampleSize; // = true; // It can easily cause memory overflow bitmap = (inStream, null, opt); // bitmap = (path, opt); if (inStream != null) { try { (); } catch (IOException e) { (); } finally { inStream = null; } } if (bitmap == null) { return null; } Matrix m = new Matrix(); if (degree != 0) { //Set the rotation angle for Matrix (degree); bitmap = (bitmap, 0, 0, (), (), m, true); } float scaleValue = (float) specifiedWidth / (); // Equal compression (scaleValue, scaleValue); bitmap = (bitmap, 0, 0, (), (), m, true); return bitmap; } catch (OutOfMemoryError e) { (); return null; } catch (Exception e) { (); return null; } } /** * Read image properties: rotation angle * * @param path Source information * Absolute path to the picture * @return degree rotation angle */ public static int readPictureDegree(String path) { int degree = 0; try { ExifInterface exifInterface = new ExifInterface(path); int orientation = (ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL); switch (orientation) { case ExifInterface.ORIENTATION_ROTATE_90: degree = 90; break; case ExifInterface.ORIENTATION_ROTATE_180: degree = 180; break; case ExifInterface.ORIENTATION_ROTATE_270: degree = 270; break; } } catch (IOException e) { (); } return degree; } public static void copyStream(InputStream inputStream, OutputStream outStream) throws Exception { try { byte[] buffer = new byte[1024]; int len = 0; while ((len = (buffer)) != -1) { (buffer, 0, len); } (); } catch (IOException e) { (); }finally { if(inputStream != null){ (); } if(outStream != null){ (); } } } }
SDcardutils:
package .czx10; import ; import ; import ; import ; /** * Created by czx on 2017/9/27. */ public class SDCardUtils { public static final String DLIAO = "dliao" ; public static File photoCacheDir = (().getAbsolutePath() + + DLIAO); public static String cacheFileName = ""; public static boolean isSDCardExist() { if (().equals(Environment.MEDIA_MOUNTED)) { return true; } else { return false; } } public static void delFolder(String folderPath) { try { delAllFile(folderPath); String filePath = folderPath; filePath = (); File myFilePath = new File(filePath); (); } catch (Exception e) { (); } } public static boolean delAllFile(String path) { boolean flag = false; File file = new File(path); if (!()) { return flag; } if (!()) { return flag; } String[] tempList = (); File temp = null; for (int i = 0; i < ; i++) { if (()) { temp = new File(path + tempList[i]); } else { temp = new File(path + + tempList[i]); } if (()) { (); } if (()) { delAllFile(path + "/" + tempList[i]);// Delete the files in the folder first delFolder(path + "/" + tempList[i]);// Delete the empty folder again flag = true; } } return flag; } public static boolean deleteOldAllFile(final String path) { try { new Thread(new Runnable() { @Override public void run() { delAllFile(() + + DLIAO); } }).start(); } catch (Exception e) { (); return false; } return true; } /** * Get folder for given string * * @param dirPath * @return Full path to the folder created */ public static File createCacheDir(String dirPath) { File dir = new File(dirPath);; if(isSDCardExist()){ if (!()) { (); } } return dir; } public static File createNewFile(File dir, String fileName) { File f = new File(dir, fileName); try { // There has been a situation where the directory does not exist, recreate it if (!()) { (); } (); } catch (IOException e) { (); } return f; } public static File getCacheFile() { return createNewFile(photoCacheDir, cacheFileName); } public static File getMyFaceFile(String fileName) { return createNewFile(photoCacheDir, fileName); } /** * Get the remaining storage space of SDCARD * * @return 0 sd has been mounted and occupied 1 sd card memory is insufficient 2 sd available */ public static int getAvailableExternalStorageSize() { if (isSDCardExist()) { File path = (); StatFs stat = new StatFs(()); long blockSize = (); long availableBlocks = (); long memorySize = availableBlocks * blockSize; if(memorySize < 10*1024*1024){ return 1; }else{ return 2; } } else { return 0; } } }
This way you can upload pictures to the Internet!
The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.