2011-11-21 2 views
4

Может ли кто-нибудь помочь мне узнать: Как отправить данные типа текста и изображения через многостраничную форму данных в javascript для моего api. Пожалуйста, помогите мне в решении моего вопроса.MultiPart Данные в Javascript

function apiCall(url){ 
     var myJsonObj ; 

     if (window.XMLHttpRequest) 
     {// code for IE7+, Firefox, Chrome, Opera, Safari 
      xmlhttp=new XMLHttpRequest(); 
      } 
      else 
      {// code for IE6, IE5 
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); 
      } 
      xmlhttp.open("POST",url,true); 
      xmlhttp.send(); 
      xmlhttp.onreadystatechange=function() 
      { 
       if (xmlhttp.readyState==4 && xmlhttp.status==200) 
       { 

       // document.getElementById("myDiv").innerHTML=xmlhttp.responseText; 
       myJsonObj = JSON.parse(xmlhttp.responseText); 
        if(myJsonObj.SS == "TRUE"){ 
         window.location = "index.jsp"; 
        } 


       } 
      } 
     } 

Этот набор кодов не работает для отправки данных Multipart.

Спасибо заранее.

+0

Привет, Добро пожаловать в SO. Укажите код. – MeLight

+0

Вы можете использовать скрытую форму, которая отправляет скрытый iFrame. Или вы можете закодировать изображение как base64 и просто отправить его как обычную переменную. – Gerben

ответ

1

Как насчет xmlhttp.setRequestHeader("Content-Type", "multipart/form-data"); где-то между open() и отправкой (данными)?

1

я решил проблему многочастного таким образом:

функция SendData() {

var boundary = generateBoundary(); 

    var url = "http://localhost:8084/MagicFolder/enterProductDetails?"; 
    var xhr = new XMLHttpRequest; 

    xhr.open("POST", url, true); 
    xhr.onreadystatechange = function() { 
    if (xhr.readyState === 4) { 
    alert("Your Response is:" +xhr.responseText); 
    } 
    }; 
    var contentType = "multipart/form-data; boundary=" + boundary; 
    xhr.setRequestHeader("Content-Type", contentType); 

    // for (var header in this.headers) { 
    // xhr.setRequestHeader(header, headers[header]); 
    // } 

    // here's our data variable that we talked about earlier 

    var data =buildMessage(getelements(), boundary); 
    alert("Your Final Data is" +data); 
    // finally send the request as binary data 
    xhr.sendAsBinary(data); 
    } 




    function getelements() { 
     var fields = []; 

     // gather INPUT elements 
     var inputs = document.getElementsByTagName("input"); 
     for (var l=inputs.length, i=0; i<l;i++){ 
     fields.push(inputs[i]); 

     } 

     // gather SELECT elements 
     var selects = document.getElementsByTagName("SELECT"); 
     for (var l=selects.length, i=0; i<l;i++){ 
      fields.push(selects[i]); 
     } 

     return fields; 
    } 


    function generateBoundary() { 
    // alert("AJAX-----------------------" + (new Date).getTime()); 
    // genboundary= "AJAX-----------------------" + (new Date).getTime(); 
    // alert(genboundary); 
    // return "AJAX-----------------------" + (new Date).getTime()); 
     return ("AJAX-----------------------"); 
    } 



    function buildMessage(getelements, boundary) { 

     //alert("helllloooooooooooooooooooojjjjjjjjjjj"+getelements); 
    var CRLF = "\r\n"; 
    var parts = []; 
    // alert(getelements()); 
    getelements.forEach(function(element, index, all) { 

    var part = ""; 
    var type = "TEXT"; 

    if (element.nodeName.toUpperCase() === "INPUT") { 
    type = element.getAttribute("type").toUpperCase(); 
    } 

    if (type === "FILE" && element.files.length > 0) { 
    var fieldName = element.name; 
    var fileName = element.files[0].fileName; 

    /* 
    * Content-Disposition header contains name of the field 
    * used to upload the file and also the name of the file as 
    * it was on the user's computer. 
    */ 
    part += 'Content-Disposition: form-data; '; 
    part += 'name="' + fieldName + '"; '; 
    part += 'filename="'+ fileName + '"' + CRLF; 

    /* 
    * Content-Type header contains the mime-type of the file 
    * to send. Although we could build a map of mime-types 
    * that match certain file extensions, we'll take the easy 
    * approach and send a general binary header: 
    * application/octet-stream 
    */ 
    part += "Content-Type: application/octet-stream"; 
    part += CRLF + CRLF; // marks end of the headers part 

    /* 
    * File contents read as binary data, obviously 
    */ 
    part += element.files[0].getAsBinary() + CRLF; 
    } else { 
    /* 
    * In case of non-files fields, Content-Disposition 
    * contains only the name of the field holding the data. 
    */ 
     if (element.nodeName.toUpperCase() === "INPUT") { 
      type = element.getAttribute("type").toUpperCase(); 
     } 

     if (type === "TEXT" || type==="SELECT") { 

      part += 'Content-Disposition: form-data; '; 
      part += 'name="' + element.name + '"' + CRLF + CRLF; 

      /* 
      * Field value 
      */ 
      part += element.value + CRLF; 
     } 
    } 
    parts.push(part); 
    }); 

    var request = "--" + boundary + CRLF; 
    request+= parts.join("--" + boundary + CRLF); 
    request+= "--" + boundary + "--" + CRLF; 

    return request; 
    } 


    Note: This set of code works fine for the multipart data. 
Смежные вопросы