直接上代碼:
@Log("新增論帖內容圖片上傳")
@RequestMapping("/upload")
@ResponseBody
public JSONObject uploadImgToOSS(HttpServletRequest request, HttpServletResponse response) {
JSONObject jsonObject=new JSONObject();
try {
request.setCharacterEncoding("UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
Part part = null;
try {
part = request.getPart("myFileName");// myFileName是文件域的name屬性值
} catch (IOException e) {
e.printStackTrace();
} catch (ServletException e) {
e.printStackTrace();
}
// 包含原始文件名的字符串
String fi = part.getHeader("content-disposition");
// 提取文件拓展名
String fileNameExtension = fi.substring(fi.indexOf("."), fi.length() - 1);
// 生成實際存儲的真實文件名
String realName = UUID.randomUUID().toString() + fileNameExtension;
// 圖片存放的真實路徑
String realPath = "http://ssbbs.oss-cn-****.aliyuncs.com/文件夾目錄/" + realName;
// 將文件寫入指定路徑下
OSSClient client = new OSSClient("oss存儲服務地址", "addressId", "addressKey" +
"");
String dir = "文件夾目錄/";
String ossUrl = "";
try {
InputStream inputStream = part.getInputStream();
ossUrl = dir + realName;
client.putObject("ssbbs", ossUrl, inputStream);
} catch (Exception e) {
e.printStackTrace();
}
client.shutdown();
// 返回圖片的URL地址
JSONArray jsonArray=new JSONArray();
jsonArray.add(realPath);
jsonObject.put("errno",0);
jsonObject.put("data",jsonArray);
return jsonObject;
}