随便取个名字_哈哈
2020-06-25 15:02:06
好用的免费图床+java后台上传图片代码
上次推荐的免费图床只有1个g,而且只用postman做了测试,今天推荐1个100g的免费图床+java后台代码上传测试
他的地址为:https://images.ac.cn/
1.看api需要什么参数
public class UploadConstant { public static final String API_TYPE = "ali"; public static final String PRIVATE_STRORAGE = "oss"; public static final String TOKEN = "填写自己的token"; public static final String URL = "https://images.ac.cn/api/upload/upload"; }
2.上传代码
public class UploadUtil { public static JSONObject uploadImg(File image, String apiType, String privateStorage, String token, String url) { RequestBody fileBody = RequestBody.create(MediaType.parse("image/*"), image); OkHttpClient client = new OkHttpClient(); JSONObject jsonObject = null; RequestBody requestBody = new MultipartBody.Builder() .setType(MultipartBody.FORM) .addFormDataPart("image", image.getName(), fileBody) .addFormDataPart("apiType", apiType) .addFormDataPart("privateStorage", privateStorage) .addFormDataPart("token", token) .build(); System.out.println(requestBody.toString()); Request request = new Request.Builder() .url(url) .post(requestBody) .build(); Response response; try { response = client.newCall(request).execute(); String jsonString = response.body().string(); jsonObject = JSON.parseObject(jsonString); System.out.println("返回:"+jsonObject.getJSONObject("data").getJSONObject("url").getString("ali")); if(!jsonObject.getString("code").equals("200")){ System.out.println("图片上传土豆图床错误。。。。"); }else{ } } catch (IOException e) { }catch (JSONException e){ } return jsonObject; } //获取流文件 public static void inputStreamToFile(InputStream ins, File file) { try { OutputStream os = new FileOutputStream(file); int bytesRead = 0; byte[] buffer = new byte[8192]; while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) { os.write(buffer, 0, bytesRead); } os.close(); ins.close(); } catch (Exception e) { e.printStackTrace(); } } }
3,.上传返回图片url:
@RequestMapping(value = "/uploadImg", method = RequestMethod.POST) public @ResponseBody String uploadImg(@RequestParam("photo") MultipartFile file, HttpServletRequest request) throws IllegalStateException, IOException { File toFile = null; if (file.equals("") || file.getSize() <= 0) { file = null; } else { InputStream ins = null; ins = file.getInputStream(); toFile = new File(file.getOriginalFilename()); UploadUtil.inputStreamToFile(ins, toFile); ins.close(); } String url = UploadUtil.uploadImg(toFile, UploadConstant.API_TYPE,UploadConstant.PRIVATE_STRORAGE,UploadConstant.TOKEN,UploadConstant.URL).getJSONObject("data").getJSONObject("url").getString("ali"); System.out.println("图片url:"+url); return url; }
返回的url:
查看自己的图床是否上传了:
注意:后台上传图片,主要用到了okhttp3这个jar,他的pom配置为:
<!-- https://mvnrepository.com/artifact/com.squareup.okhttp3/okhttp --> <dependency> <groupId>com.squareup.okhttp3</groupId> <artifactId>okhttp</artifactId> <version>4.4.0</version> </dependency>
评论