I've written a code about using Retrofit to upload picture files, but what if OkHttp is used? I believe that some of the students who know about the two know that in fact the implementation of Retrofit's internal network request is OkHttp. After wrapping one layer, it is just for the convenience of developers to write interfaces and use them in combination with RxJava, so the code difference is not very big.
There is no good encapsulation here, just a demo, when you actually use okHttp encapsulation layer will be better. My own language is Kotlin, but for the sake of convenience, I will paste the Java version of the code on it. As for the background code, it is the same as the last article, but because the name has changed, I will give it all. If you have any questions, please point out and ask them.
// Method of uploading background pictures fun uploadBgImg(userid: String, imgPath: String, listener: UploadListener) { var file: File? = null try { file = File(imgPath) } catch (e: URISyntaxException) { e.printStackTrace() } val mOkHttpClent = OkHttpClient() val requestBody = MultipartBody.Builder() .setType(MultipartBody.FORM) .addFormDataPart("userid", userid) // Upload parameters .addFormDataPart( "bgImg", file?.name, RequestBody.create(MediaType.parse("multipart/form-data"), file!!) ) // Upload files .build() val request = Request.Builder() .url(ConstantConfig.JACKSON_BASE_URL + "phoneUser/uploadBgImg") .post(requestBody) .build() val call = mOkHttpClent.newCall(request) call.enqueue(object : Callback { override fun onFailure(call: Call, e: IOException) { LogUtils.e("yyy" + e.message) listener.uploadFailed(e.message.toString()) } override fun onResponse(call: Call, response: Response) { if (response.isSuccessful) { listener.uploadSuccess() } else { listener.uploadSuccess() LogUtils.e("tttttt" + response.code() + response.message()) } } }) }
Interface file
interface UploadListener { fun uploadSuccess() fun uploadFailed(msg: String) }
Actual call location
//Upload background pictures private fun uploadBgImg(path: String) { UploadUtils.uploadBgImg(App.getLoginUser()?.userid!!, path, object : UploadUtils.UploadListener { override fun uploadSuccess() { runOnUiThread { userBgImage.setImageBitmap(BitmapFactory.decodeFile(path)) } LogUtils.e("ModifyUserInfo Success") } override fun uploadFailed(msg: String) { LogUtils.e("ModifyUserInfo" + msg) } }) }
It should be noted here that the thread returned by okHttp by default is a sub-thread rather than a main thread. So if we need to do something, we still need the runOnUiThread method to switch to the main thread. If you have free time, you can encapsulate it. You can use it through Handle. After all, it is the master of asynchronous processing in Android.
Background code, note that the parameter name here is different from the last one, so don't make mistakes if the copy code is used.
/** * Upload User Background Pictures */ @RequestMapping(value = "/uploadBgImg", method = RequestMethod.POST) @ResponseBody public Map<String, Object> uploadBgImg(@RequestParam("userid") String userid, @RequestBody MultipartFile bgImg) { // The MultipartFile class is used to upload avatars in the spring family. Multiple files are array types System.out.println("Enter Background Picture Upload Interface"); System.out.println("Filename:" + bgImg.getOriginalFilename() + "\n" + "userid: " + String.valueOf(userid)); Map<String, Object> map = new HashMap<>(); if (!bgImg.isEmpty()) { String originalFileName = bgImg.getOriginalFilename(); String mimeType = request.getServletContext().getMimeType(originalFileName); System.out.println("mimeType: " + mimeType); // Is it a picture file? if (mimeType != null && mimeType.startsWith("image/")) { try { String suffix = originalFileName.split("\\.")[1]; // Extension name // upload folder to project root directory String avatarPath = request.getSession().getServletContext().getRealPath("/upload") + // File.separator + user.getUsername() + File.separator + "avatar" + File.separator + System.currentTimeMillis() + "." + suffix; String savePath = avatarPath.substring(avatarPath.indexOf("\\upload")); String finPath = savePath.replaceAll("\\\\", "/"); System.out.println("savePath: " + savePath); System.out.println("finPath: " + finPath); /** * Upload to a specific hard disk path, at which point you need to configure tomcat virtual path */ // String avatarPath = "I:" + File.separator + "ProjectsFolder" + File.separator + "IdeaProject" // + File.separator + "MovieProject" + File.separator + "src" + File.separator + "main" // + File.separator + "webapp" + File.separator + "upload" + File.separator + user.getUsername() // + File.separator + "avatar" + File.separator + System.currentTimeMillis() + "." + suffix; System.out.println("tomcatPath: " + avatarPath); File saveFile = new File(avatarPath); if (!saveFile.getParentFile().exists()) { saveFile.getParentFile().mkdirs(); saveFile.createNewFile(); } bgImg.transferTo(saveFile); //Upload files to the specified server location int rows = userService.updateUserAvatar(userid, finPath.substring(1)); // The path stored in the database starts with upload. // The sub here is to remove the first'/' if (rows > 0) { System.out.println("Successful uploading of background pictures"); // // Query the user after uploading the file successfully, and then return the latest user PhoneUser user = userService.getUserInfo(userid); if (user != null) { map.put("data", user); map = CommonUtils.operationSucceed(map); } else { map = CommonUtils.operationFailed(map, "other error", HttpStatus.NOT_FOUND.value()); } } else { System.out.println("Failed to upload background picture"); map = CommonUtils.operationFailed(map, "change data failed", HttpStatus.BAD_REQUEST.value()); } } catch (IOException e) { // Error in upload process System.out.println(e.getMessage()); map = CommonUtils.operationFailed(map, "upload fail", HttpStatus.INTERNAL_SERVER_ERROR.value()); e.printStackTrace(); } } else { // Not a picture file returns relevant information map = CommonUtils.operationFailed(map, "please upload an image file", HttpStatus.BAD_REQUEST.value()); } // Empty file return correlation } else { System.out.println("empty file"); map = CommonUtils.operationFailed(map, "empty file", HttpStatus.BAD_REQUEST.value()); } return map; }
By the time this code is finished, the comments are rich enough to be understood by everyone. Next, I will post the Java version of the front code for your reference.
// Method of uploading background pictures public static void uploadBgImg(String userid, String imgPath, final UploadUtils.UploadListener listener) { File file = null; try { file = new File(imgPath); } catch (Exception e) { e.printStackTrace(); } OkHttpClient mOkHttpClent = new OkHttpClient(); assert file != null; MultipartBody requestBody = new MultipartBody.Builder() .setType(MultipartBody.FORM) .addFormDataPart("userid", userid) // Upload parameters .addFormDataPart( "bgImg", file.getName(), RequestBody.create(MediaType.parse("multipart/form-data"), file) ) // Upload files .build(); Request request = new Request.Builder() .url(ConstantConfig.JACKSON_BASE_URL + "phoneUser/uploadBgImg") .post(requestBody) .build(); Call call = mOkHttpClent.newCall(request); call.enqueue(new Callback() { @Override public void onFailure(@NonNull Call call, @NonNull IOException e) { listener.uploadFailed(e.getMessage()); } @Override public void onResponse(@NonNull Call call, @NonNull Response response) { if (response.isSuccessful()) listener.uploadSuccess(); } }); }
Believe that small partners can write it out themselves, but unfortunately AS only provides Java to Kotlin plug-ins, no Kotlin to Java plug-ins. So I can only write by myself.
May we be real ourselves, refueling together