使用Ajax文件上传?

时间:2013-08-07 09:39:30

标签: javascript jquery ajax impromptu

我正在使用Impromptu Api进行对话框的网页,其中包含html表单:

            html = '<label>Name&nbsp;&nbsp;&nbsp;&nbsp;<input type="text" id="fname" name="fname" value="'+STUDENT_NAME+'"></label><br />'
                        + '<label>Sex<select id="sex"> <option value="m" >Male</option>   <option value="f" selected>Female</option>'
                        + '</select>'
                        + '</label><br />'
                        + '<label>Category<select id="cat"> <option value="a">A</option>   <option value="b" selected>B</option>'
                        + '</select>' + '</label>'+
                        '<input type="file" id="logo">'+ 
                        '<br />';

使用Ajax提交如下表单:

         $.ajax({
                        url : 'AddStudent.jsp',
                        data : 'classId=' +
                                 <%=class_id%>
                                + '&name='
                                + document.getElementById('fname').value
                                + '&cat='
                                + document.getElementById('cat').value
                                + '&func=del' + '&sex='
                                + document.getElementById('sex').value,
                        type : 'post',
                        success : function(msg) {
                                              //events}

我有代码上传这样的文件:

             String saveFile = "";
  String contentType = request.getContentType();
  if ((contentType != null) && (contentType.indexOf("multipart/form-data") >= 0)) {
        DataInputStream in = new DataInputStream(request.getInputStream());
        int formDataLength = request.getContentLength();
        byte dataBytes[] = new byte[formDataLength];
        int byteRead = 0;
        int totalBytesRead = 0;
        while (totalBytesRead < formDataLength) {
              byteRead = in.read(dataBytes, totalBytesRead, formDataLength);
              totalBytesRead += byteRead;
        }
        String file = new String(dataBytes);
        saveFile = file.substring(file.indexOf("filename=\"") + 10);
        saveFile = saveFile.substring(0, saveFile.indexOf("\n"));
        saveFile = saveFile.substring(saveFile.lastIndexOf("\\") + 1, saveFile.indexOf("\""));
        int lastIndex = contentType.lastIndexOf("=");
        String boundary = contentType.substring(lastIndex + 1, contentType.length());
        int pos;
        pos = file.indexOf("filename=\"");
        pos = file.indexOf("\n", pos) + 1;
        pos = file.indexOf("\n", pos) + 1;
        pos = file.indexOf("\n", pos) + 1;
        int boundaryLocation = file.indexOf(boundary, pos) - 4;
        int startPos = ((file.substring(0, pos)).getBytes()).length;
        int endPos = ((file.substring(0, boundaryLocation)).getBytes()).length;
        saveFile = "D:/SERVERE/" + saveFile;
        File ff = new File(saveFile);
        FileOutputStream fileOut = new FileOutputStream(ff);
        fileOut.write(dataBytes, startPos, (endPos - startPos));
        fileOut.flush();
        fileOut.close();

  }

但这不适用于Ajax方法。我希望文件必须上传到同一页面。怎么可以使用Ajax完成,还是有其他技术?请帮助

2 个答案:

答案 0 :(得分:1)

如果您可以使用HTML5文件API和FormData对象。

var xhr = new XMLHttpRequest();
xhr.upload.addEventListener('progress',function(ev){
    console.log((ev.loaded/ev.total)+'%');
}, false);
xhr.onreadystatechange = function(ev){
    // Blah blah blah, you know how to make AJAX requests
};
xhr.open('POST', url, true);
var files = document.getElementById('logo').files;
var data = new FormData();
for(var i = 0; i < files.length; i++) data.append('file'+i, files[i]);
xhr.send(data);

您可以执行data.append('name',document.getElementById('name'))等附加所有其他表单字段。

答案 1 :(得分:0)

这可能会对你有所帮助

<input id="avatar" type="file" name="avatar" />
<button id="upload" value="Upload" />

然后

$("#upload").live("click", function() {
    var file_data = $("#avatar").prop("files")[0];   // Getting the properties of file from file field
    var form_data = new FormData();                  // Creating object of FormData class
    form_data.append("file", file_data)              // Appending parameter named file with properties of file_field to form_data
    form_data.append("user_id", 123)                 // Adding extra parameters to form_data
    $.ajax({
                url: "/upload_avatar",
                dataType: 'script',
                cache: false,
                contentType: false,
                processData: false,
                data: form_data,                         // Setting the data attribute of ajax with file_data
                type: 'post'
       })
})
相关问题