Android上傳圖片到伺服器並顯示(後臺用Java處理)
阿新 • • 發佈:2018-12-11
Android上傳圖片(Android Studio)
Fragment介面:
private String img_src; /** * 從相簿選取圖片 */ public void selectImg() { 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, SELECT_PHOTO); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); switch (requestCode) { case SELECT_PHOTO: switch (resultCode) { case RESULT_OK: Uri uri = data.getData(); img_src = uri.getPath();//這是本機的圖片路徑 ContentResolver cr = getActivity().getContentResolver(); try { Bitmap bitmap = BitmapFactory.decodeStream(cr.openInputStream(uri)); /* 將Bitmap設定到ImageView */ imageView.setImageBitmap(bitmap); String[] proj = {MediaStore.Images.Media.DATA}; CursorLoader loader = new CursorLoader(getContext(), uri, proj, null, null, null); Cursor cursor = loader.loadInBackground(); if (cursor != null) { int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); cursor.moveToFirst(); img_src = cursor.getString(column_index);//圖片實際路徑 } cursor.close(); } catch (FileNotFoundException e) { Log.e("Exception", e.getMessage(), e); } break; } break; } } public void uploadImage(String path) { new Thread(new Runnable() { @Override public void run() { String uploadurl = SharedPreferencesUtil.getServerUrls(getActivity()) + "mobileqrcode/uploadsignimg.html"; try { File file = new File(img_src); result = UploadUtil.uploadImage(file, uploadurl); } catch (Exception e) { e.printStackTrace(); } } }).start(); }
上傳檔案工具類:
public class UploadUtil { private static final String TAG = "uploadFile"; private static final int TIME_OUT = 10 * 1000;//超時時間 private static final String CHARSET = "utf-8";//設定編碼 /** * android上傳檔案到伺服器 * * @param file 需要上傳的檔案 * @param RequestURL 請求的url * @return 返回響應的內容 */ public static String uploadImage(File file, String RequestURL) { String result = "error"; String BOUNDARY = UUID.randomUUID().toString();//邊界標識 隨機生成 String PREFIX = "--", LINE_END = "\r\n"; String CONTENT_TYPE = "multipart/form-data";//內容型別 try { URL url = new URL(RequestURL); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(TIME_OUT); conn.setConnectTimeout(TIME_OUT); 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); conn.connect(); if (file != null) { //當檔案不為空,把檔案包裝並且上傳 DataOutputStream dos = new DataOutputStream(conn.getOutputStream()); /*StringBuilder sb = new StringBuilder(); sb.append(PREFIX); sb.append(BOUNDARY); sb.append(LINE_END); *//* * 這裡重點注意: * name裡面的值為伺服器端需要key,只有這個key才可以得到對應的檔案 * filename是檔案的名字,包含字尾名的。比如:abc.png *//* sb.append("Content-Disposition: form-data; name=\"inputName\"; filename=\"" + file.getName() + "\"" + LINE_END); //sb.append("Content-Type: application/octet-stream; charset=" + CHARSET + LINE_END); //sb.append("Content-Type: " + getMIMEType(file) + LINE_END); sb.append(LINE_END); dos.write(sb.toString().getBytes());*///此寫法會導致無法上傳 dos.writeBytes(PREFIX + BOUNDARY + LINE_END); dos.writeBytes("Content-Disposition: form-data; " + "name=\"inputName\";filename=\"" + file.getName() + "\"" + LINE_END); dos.writeBytes(LINE_END); FileInputStream is = new FileInputStream(file); byte[] bytes = new byte[1024]; int len = -1; 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(); if (res == 200) { InputStream input = conn.getInputStream(); StringBuilder sbs = new StringBuilder(); int ss; while ((ss = input.read()) != -1) { sbs.append((char) ss); } result = sbs.toString(); Log.i(TAG, "result------------------>>" + result); } } } catch (IOException e) { e.printStackTrace(); } return result; } private static String getMIMEType(File file) { String fileName = file.getName(); if (fileName.endsWith("png") || fileName.endsWith("PNG")) { return "image/png"; } else { return "image/jpg"; } } }
Java端接收圖片(Eclipse)
@RequestMapping(value = "/uploadsignimg", method = RequestMethod.POST) public void uploadOrderSignImage(HttpServletRequest request, HttpSession session, HttpServletResponse response) { try { MultipartHttpServletRequest rq = (MultipartHttpServletRequest) request; Map<String, MultipartFile> file_list = rq.getFileMap(); if (file_list != null && file_list.size() > 0) { if (file_list.containsKey("inputName")) { MultipartFile file = file_list.get("inputName"); if (file != null) { // 儲存訂單簽收圖片 String fileName = file.getOriginalFilename(); String newFileName = ""; String[] desp = fileName.split("\\."); if (desp != null && desp.length > 0) { String extendName = desp[desp.length - 1]; newFileName = new Date().getTime() + "." + extendName; ServletContext servletContext = request.getSession().getServletContext(); String uploadPath = servletContext.getRealPath("/") + "upload\\"; File saveFile = new File(uploadPath, newFileName); file.transferTo(saveFile); } session.setAttribute("newfilename", newFileName); } } } } catch (Exception e) { e.printStackTrace(); } }