weixin_33726318 2016-01-21 19:03 采纳率: 0%
浏览 19

通过AJAX上传文件输入

While filling the form, I want my users to have a preview on what they just selected in the file input field. For this, I'm trying to avoid any kind of plugin or additional software (except for jQuery).

This is what I got, after some internet research:

    $("#file-upload").change(function() {
    var formData = new FormData($("#editForm")[0]);
    $.ajax({
        url: 'script.php',  //Server script to process data
        type: 'POST',
        xhr: function() {  // Custom XMLHttpRequest
            var myXhr = $.ajaxSettings.xhr();
            return myXhr;
        },
        //Ajax events
        success: function(output) {
            document.write(output);
        },
        error: function (xhr, ajaxOptions, thrownError) {
            alert(xhr.status);
            alert(thrownError);
        },
        // Form data
        data: formData,
        //Options to tell jQuery not to process data or worry about content-type.
        cache: false,
        contentType: false,
        processData: false
    });
});

The problem with this: formData does not contain any input fields with type="file"!

Any help is appreciated :)

  • 写回答

1条回答 默认 最新

  • weixin_33724059 2016-01-21 19:16
    关注

    This works for me:

    <input type="file" name="browseFile" id="photo" placeholder="File" />
    <input id="userId" type="text" />
    
    <input type="submit" value="create request" onclick="CreateRequest(event)" 
    
    
    <script>
          function CreateRequest(event) {
                event.preventDefault ? event.preventDefault() : event.returnValue = false;
    
                var inputFilePhoto = document.getElementById("photo");
                var imageFile = inputFilePhoto.files[0];
    
                var userId = document.getElementById("userId").value;
    
    
                var formData = new FormData();             
                formData.append("RequestPhoto", imageFile);
                formData.append("UserId", userId);
    
                $.ajax({
                    type: "POST",
                    url: "/User/CreateRequest",
                    data: formData,
                    contentType: false,
                    processData: false,
    
                    success: function () {
                        alert("OK");
                    },
                    error: function () {
                        alert("Error");
                    }
    
                });
    
    评论

报告相同问题?

悬赏问题

  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?