zoukankan      html  css  js  c++  java
  • 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("
    ").append("--").append(BOUNDARY).append("
    ");
                        strBuf.append("Content-Disposition: form-data; name="" + inputName + ""
    
    ");
                        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("
    ").append("--").append(BOUNDARY).append("
    ");
                        strBuf.append("Content-Disposition: form-data; name="" + inputName + ""; filename="" + inputName + ""
    ");
                        strBuf.append("Content-Type:" + contentType + "
    
    ");
                        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 = ("
    --" + BOUNDARY + "--
    ").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("
    ");
                }
                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());
        }
    
    }
    
  • 相关阅读:
    什么是HTTPS协议
    思维:从互联网到区块链
    BFT-SMaRt:用Netty做客户端的可靠信道
    BFT-SMaRt:用Java做节点间的可靠信道
    共识网络BFT-SMaRt:理论与实践
    EOS源码分析:transaction的一生
    勘误:EOS资源抵押退还
    如何踩中下一个技术节拍
    本人新书,欢迎抢购
    REX:EOS资源租赁平台详解
  • 原文地址:https://www.cnblogs.com/aknife/p/13782393.html
Copyright © 2011-2022 走看看