詳細的代碼過程參考網上:
//跨越的設置
Map <String,String> result = new HashMap<String,String>();
response.setHeader("Access-Control-Allow-Origin", "*");//跨域訪問··
String imgFilePath="";//寫入文件的目錄
String dbpath="";//寫入數據庫中路徑,返回可以直接訪問的
//項目路徑
String tcatpath = request.getServletContext().getRealPath("/");
System.out.println("輸出的項目路徑"+tcatpath);
//隨機數命名
Random rand = new Random();
String picName= ""+(rand.nextInt(900000)+100000);//生成6位的隨機數
//上傳圖片 到項目中的某一個文件夾中,並且對base64進行解碼
String img=request.getParameter("userPic");//接受圖片
System.out.println("測試從移動端的測試的獲取的base64的 字符串");
// String img=imgStr.replace(" ", "+");//base64解碼中注意“+”和空格的只愛電腦看到你管
BASE64Decoder decoder = new BASE64Decoder();
System.out.println("開始解碼");
try
{
//Base64解碼
byte[] b = decoder.decodeBuffer(img);
//添加到服務器的地址:http://liuwu.site/
imgFilePath = tcatpath+"\\imgUserHeard\\"+picName+".jpg";//
//拼出字符串;存入數據庫中。
dbpath="http://mishuixunhuanx.com/msxh-web-api/imgUserHeard/"+picName+".jpg";
System.out.println("輸出存儲的路徑"+imgFilePath);
OutputStream out = new FileOutputStream(imgFilePath);
logger.info("生成圖片");
out.write(b);
out.flush();
out.close();
}
catch (Exception e)
{
logger.info("解碼失敗");
}
/*****
* 圖書上傳成功。
* 插入地址,同時返回一個地址
*/