您好,登錄后才能下訂單哦!
本篇文章為大家展示了java中怎么實現后臺圖片跨域上傳功能,內容簡明扼要并且容易理解,絕對能使你眼前一亮,通過這篇文章的詳細介紹希望你能有所收獲。
在項目開發的過程中,我們經常需要用到圖片上傳操作,傳統的做法是我們將其上傳到項目的所在目錄中,比如說項目的target目錄中,但是由于項目在重啟的過程中,target文件夾下的內容會被全部清空,這意味著如果采用這種方式,那么在測試環境與開發環境;在每一次的項目重啟的過程中,我們經常會遭遇圖片丟失的情況,這種情況有時往往很讓人頭疼,因而有一個圖片服務器對于項目的開發和測試而言,這是十分必要的。
在采用圖片服務器的情況下,我們只需要像往常一樣,由前臺界面將圖片上傳到本地項目服務器中,然后本地的項目服務器會將該圖片的數據流寫入到遠程的圖片服務器中,由遠程的圖片服務器負責圖片的存儲,最后,遠程的圖片服務器會返回一個存儲圖片路徑,在本地的服務器只需要存儲該路徑,在頁面展示的時候,只需要在前臺將該圖片路徑展示出來,即可完成對于遠程圖片服務器的調用。
@ResponseBody @RequestMapping(value="/imgUpLoadNewOneKuaYu") public String imgUpLoadNewOneKuaYu(HttpServletRequest request) throws IOException { String urlStr = "http://localhost:9080/no-js/admin/upload"; Map<String, String> textMap = new HashMap<String, String>(); MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;//流的數據* //取得request中的所有文件名 Iterator<String> iter = multiRequest.getFileNames(); Map<String, InputStream> fileMap = new HashMap<String, InputStream>(); if(iter.hasNext()){ //取得上傳文件 MultipartFile file = multiRequest.getFile(iter.next()); if(file != null){ //取得當前上傳文件的文件名稱 String myFileName = file.getOriginalFilename(); InputStream fileInputStream=file.getInputStream(); fileMap.put(myFileName, fileInputStream); } } String ret = FileUpLoadNew.formUpload(urlStr, textMap, fileMap); System.out.println(ret); return ret; }
FileUpLoadNew
package net.sahv.bdyz.util;import java.io.BufferedReader;import java.io.DataInputStream;import java.io.DataOutputStream;import java.io.FileInputStream;import java.io.InputStream;import java.io.InputStreamReader;import java.io.OutputStream;import java.net.HttpURLConnection;import java.net.URL;import java.util.Iterator;import java.util.Map;public class FileUpLoadNew { /** * @param urlStr * @param textMap * @param fileMap * @return */ public static String formUpload(String urlStr, Map<String, String> textMap, Map<String, InputStream> fileMap) { String res = ""; HttpURLConnection conn = null; String BOUNDARY = "---------------------------123821742118716"; //boundary就是request頭和上傳文件內容的分隔符 try { URL url = new URL(urlStr); conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(5000); conn.setReadTimeout(30000); conn.setDoOutput(true); conn.setDoInput(true); conn.setUseCaches(false); conn.setRequestMethod("POST"); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.6)"); conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY); OutputStream out = new DataOutputStream(conn.getOutputStream()); // textMap:如果傳送的是文本內容 if (textMap != null) { StringBuffer strBuf = new StringBuffer(); Iterator<Map.Entry<String, String>> iter = textMap.entrySet().iterator(); while (iter.hasNext()) { Map.Entry<String, String> entry = iter.next(); String inputName = (String) entry.getKey(); String inputValue = (String) entry.getValue(); if (inputValue == null) { continue; } strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n"); strBuf.append("Content-Disposition: form-data; name=\"" + inputName + "\"\r\n\r\n"); strBuf.append(inputValue); } out.write(strBuf.toString().getBytes()); } //fileMap:如果傳送的是文件流 if (fileMap != null) { Iterator<Map.Entry<String, InputStream>> iter = fileMap.entrySet().iterator(); while (iter.hasNext()) { Map.Entry<String, InputStream> entry = iter.next(); String inputName = (String) entry.getKey(); FileInputStream inputValue = (FileInputStream) entry.getValue(); if (inputValue == null) { continue; } String contentType = "image/png"; StringBuffer strBuf = new StringBuffer(); strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n"); strBuf.append("Content-Disposition: form-data; name=\"" + inputName + "\"; filename=\"" + inputName + "\"\r\n"); strBuf.append("Content-Type:" + contentType + "\r\n\r\n"); out.write(strBuf.toString().getBytes()); DataInputStream in = new DataInputStream(inputValue); int bytes = 0; byte[] bufferOut = new byte[1024]; while ((bytes = in.read(bufferOut)) != -1) { out.write(bufferOut, 0, bytes); } in.close(); } } byte[] endData = ("\r\n--" + BOUNDARY + "--\r\n").getBytes(); out.write(endData); out.flush(); out.close(); // 讀取返回數據 StringBuffer strBuf = new StringBuffer(); BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line = null; while ((line = reader.readLine()) != null) { strBuf.append(line).append("\n"); } res = strBuf.toString(); reader.close(); reader = null; } catch (Exception e) { System.out.println("發送POST請求出錯。" + urlStr); e.printStackTrace(); } finally { //最后關閉鏈接 if (conn != null) { conn.disconnect(); conn = null; } } return res; }}
package com.lyc.noJs.controller;import com.google.common.base.Splitter;import com.lyc.noJs.util.ImgMD5Util;import lombok.extern.slf4j.Slf4j;import org.joda.time.DateTime;import org.springframework.stereotype.Controller;import org.springframework.util.MultiValueMap;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.bind.annotation.ResponseBody;import org.springframework.web.multipart.MultipartFile;import org.springframework.web.multipart.MultipartHttpServletRequest;import java.io.*;import java.security.NoSuchAlgorithmException;import java.util.Iterator;import java.util.List;import java.util.Map;import java.util.Set;@Controller@RequestMapping("/admin")@Slf4jpublic class UploadController { @ResponseBody @RequestMapping(value = "/upload",method= RequestMethod.POST) public String upload(MultipartHttpServletRequest multiRequest) throws UnsupportedEncodingException { //圖片文件夾根路徑 //TODO //這里的父路徑暫時是target路徑,在真實上線后,應該將其改成其它路徑。 String uploadFilePath = multiRequest.getServletContext().getRealPath("/upload/"); //圖片文件夾日期路徑 String datePath = getDateFolderName() + "\\"; //圖片名稱 String imagePath = saveImage(multiRequest,uploadFilePath,datePath); log.info(imagePath); return imagePath; } /** * 保存圖片 * @param multiRequest * @param uploadFilePath * @param datePath * @return * @throws UnsupportedEncodingException */ public String saveImage(MultipartHttpServletRequest multiRequest,String uploadFilePath,String datePath) throws UnsupportedEncodingException { String imageNameHead = createImageNameHead(); String imageName = ""; //設置圖片的瀏覽為utf-8格式,防止圖片名稱亂碼 multiRequest.setCharacterEncoding("utf-8"); MultiValueMap<String, MultipartFile> multiFileMap = multiRequest.getMultiFileMap(); Set<Map.Entry<String, List<MultipartFile>>> set = multiFileMap.entrySet(); Iterator<Map.Entry<String, List<MultipartFile>>> iterator = set.iterator(); while(iterator.hasNext()){ Map.Entry<String, List<MultipartFile>> entry = iterator.next(); String imageNameEnd = getImageNameEnd(entry); imageName = imageNameHead + "." + imageNameEnd; List<MultipartFile> multipartFileList = entry.getValue(); MultipartFile multipartFile = multipartFileList.get(0); //圖片文件的包路徑 String imagePath = uploadFilePath + datePath; //如果文件夾創建失敗,則返回null if(makeParentFolder(imagePath)){ //如果文件夾創建失敗,則返回false,否則返回true //圖片文件的路徑 String imgFile = imagePath + imageName; //如果文件創建失敗,則返回null if(!makeImage(multipartFile,imgFile)){ //當文件創建失敗時,返回false,否則返回true return null; } } else { return null; } } return datePath + imageName; } /** * 創建圖片 * @param multipartFile * @param imgFile * @return */ public boolean makeImage(MultipartFile multipartFile,String imgFile){ File tempFile = new File(imgFile); if(tempFile != null){ //如果原圖片不存在,則生成圖片 if(!tempFile.exists()){ try { log.info("1"); multipartFile.transferTo(tempFile); } catch (IOException e) { e.printStackTrace(); } } return true; } return false; } /** * 創建父文件路徑 * @param imagePath * @return */ public boolean makeParentFolder(String imagePath){ File parentFile = new File(imagePath); if(parentFile != null){ while (!parentFile.exists()){ //批量生成全部的父文件路徑 parentFile.mkdirs(); } return true; } return false; } /** * 文件夾生成規則 */ public String getDateFolderName(){ DateTime dataTime = new DateTime(); String currentDate = dataTime.toString("yyyy\\MM\\dd"); return currentDate; } /** * 創建圖片文件的文件名 * @return */ public String createImageNameHead(){ DateTime dataTime = new DateTime(); return String.valueOf(dataTime.getMillis()); }}
上述內容就是java中怎么實現后臺圖片跨域上傳功能,你們學到知識或技能了嗎?如果還想學到更多技能或者豐富自己的知識儲備,歡迎關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。