记一次跨域上传图片

后端代码 :

@RequestMapping("uploadImg")
    public void  testUpLoad(HttpServletResponse response,@RequestParam("file") CommonsMultipartFile[] files) throws IOException {
        String url = "http://127.0.0.1:8089/file/UploadImg";
        String res = formUpload(url,files);
        response.getWriter().print(res);
    }
    public static String formUpload(String urlStr,CommonsMultipartFile[] cmfile) {
        String res = "";
        HttpURLConnection conn = null;
        // boundary就是request头和上传文件内容的分隔符
        String BOUNDARY = "---------------------------123821742118716";
        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());
            // file
            for (CommonsMultipartFile files: cmfile) {
                CommonsMultipartFile cFile = (CommonsMultipartFile) files;
                String filename = cFile.getOriginalFilename();
                if (filename.endsWith(".png")||filename.endsWith(".jpg") || filename.endsWith(".jpeg") || filename.endsWith(".jpe")||filename.endsWith(".gif")||filename.endsWith(".ico")) {
                    String  contentType = cFile.getContentType();
                    String inputName ="files";

                    // System.out.println("filename==>"+filename);
                    //System.out.println("contentType=========="+contentType);
                    StringBuffer strBuf = new StringBuffer();
                    strBuf.append("\r\n").append("--").append(BOUNDARY)
                            .append("\r\n");
                    strBuf.append("Content-Disposition: form-data; name=\""
                            + inputName + "\"; filename=\"" + filename
                            + "\"\r\n");
                    strBuf.append("Content-Type:" + contentType + "\r\n\r\n");
                    out.write(strBuf.toString().getBytes());

                    DiskFileItem fileItem = (DiskFileItem) cFile.getFileItem();
                    File file = fileItem.getStoreLocation();
                    DataInputStream in = new DataInputStream(new FileInputStream(file));
                    int bytes = 0;
                    byte[] bufferOut = new byte[1024];
                    while ((bytes = in.read(bufferOut)) != -1) {
                        out.write(bufferOut, 0, bytes);
                    }
                    in.close();
                }else {
                    return "error";
                }
            }
            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;
    }

前端代码:

//点击上传按钮 触动掩藏了的<input id='inp_file2'  type='file'> 
$(".userWallimg").click(function(){
       var wallsum = allfile.length;
        if(wallsum<5){
            $("#inp_file2").click();
        }else {
            alert("不能再多了")
        }

    });    
//图片上传按钮
    var allfile = new Array();
    $("#inp_file2").change(function(){
        var files = this.files;
        var filessum=files.length;
        for(var i=0;i<filessum;i++){
            var file=files[i];
            allfile.push(file);
            var url = URL.createObjectURL(file);
            if (parseInt(file.size / 1024) > 3000) {
                alert("张图片大小超过3000kb,请重新上传")
            }else{
                //根据图片的尺寸 对展示的效果进行调整
                var img = new Image();
                img.src=url;
                
                img.onload = function(){
                    console.log("ggggggg")
                    var timestamp = Date.parse(new Date());
                    if(img.width>img.height){
                        $("#usershowWallimg").append("<div class='upload_div2'><div class='fileimg_wall'><button id='"+file.name+"' class='deleteimg' >移除</button></div><img id='"+timestamp+"' src='"+url+"' /></div>")
                        $("#"+timestamp+"").css({"height":"150px","width":"auto"});
                    }else{
                        $("#usershowWallimg").append("<div class='upload_div2'><div class='fileimg_wall'><button id='"+file.name+"' class='deleteimg' >移除</button></div><img id='"+timestamp+"' src='"+url+"' /></div>")
                        $("#"+timestamp+"").css({"height":"auto","width":"150px"});
                    }

                    $(".fileimg_wall").hover(function(){
                        $(this).css("background-color","rgba(0,0,0,0.8)")
                        $(this).children().show()
                    },function(){
                        $(this).css("background-color","rgba(0,0,0,0)")
                        $(this).children().hide()
                    });
                    //点击删除按钮移除图片 和数组中记录的图片
                    $(".deleteimg").click(function () {
                        var filename = $(this).attr("id")
                        $(this).parent().parent().remove();//页面中移除

                        for(var j=0;j<allfile.length;j++){
                            if(allfile[j].name == filename){
                                allfile.splice(j,1);//从数组中移除
                                break;
                            }
                        }
                    });
                }
            }
        }
    });


  function  upimg() {
        var formData = new FormData();
        var len = allfile.length;
        for(var j=0;j<len;j++){
            formData.append('file',allfile[j]);
        }
       
        $.ajax({
            url: '${url}/file/uploadImg',
            type: 'POST',
            cache: false, //上传文件不需要缓存
            data: formData,
            async: false,
            processData: false, // 告诉jQuery不要去处理发送的数据
            contentType: false, // 告诉jQuery不要去设置Content-Type请求头
            success: function (data) {
               if(data!="error"){
                 $("#userWallimg").val(data)
                }else{
                     alert('上传失败!');
                }
               
           },
            error: function (data) {
                alert('无图片上传!');
            }
        })
    }

 后端参考:https://blog.csdn.net/Icywind1/article/details/85628099

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值