java后台图片跨域上传图片 文件
转至https://blog.csdn.net/ZZY1078689276/article/details/79866513
发送方
@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; }
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") @Slf4j public 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()); } }
本文作者:___mouM
声援博主:如果您觉得文章对您有帮助,可以点击文章右下角【推荐】一下。
版权说明:本文版权归作者和博客园共有,欢迎转载。但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接,否则保留追究法律责任的权利.