JQuery AJAX 文件Ypload导致完整页面重新加载

eulz3vhy  于 2023-06-29  发布在  jQuery
关注(0)|答案(2)|浏览(143)

我有一个问题,当上传一个文件通过 AJAX ,在德调用完成后,页面重新加载,这里是代码

function Save() {
    var files1 = $("#file1").get(0).files;
    var data = new FormData();
    data.append("Data", JSON.stringify(GetData()));
    for (i = 0; i < files1.length; i++) {
        data.append("file" + i, files1[i]);
    }
    var resp =
       {
           service: "File/SaveFile",
           sender: data,
           progress: null,
           funct: null,
           antes: null,
           despues: null
       };
    var response = CallServiceUpload(resp);
    response.done(function (responseData, textStatus) {
        var controlInput = $("#file1");
        controlInput.replaceWith(controlInput = controlInput.val('').clone(true));
    });
    return response;
}

function GetData() {
    x =
    {
        ID: 1
    }
    return x;
}

this.CallServiceUpload = function (obj) { 
    return $.ajax({
        type: "POST",
        url: "api/" + obj.service,
        data: obj.sender,
        contentType: false,
        processData: false,
        error: function (message) {           
            alert(message.responseText);
        }        
    });
}

下面是使用ASP API的服务器代码

using DataManager.Estruct.DTO;
using DataManager.Logic;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;

namespace WebApp.Controllers
{
    public class FileController : ApiController
    {
        #region 

        [HttpPost]
        [ActionName("SaveFile")]
        public async Task<JObject> SaveFile()
        {
            // Check if the request contains multipart/form-data.
            var httpContent = Request.Content;
            if (!Request.Content.IsMimeMultipartContent())
            {
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }
            string root = HttpContext.Current.Server.MapPath("~/App_Data");
            try
            {
                StringBuilder sb = new StringBuilder(); // Holds the response body
                var provider = new CustomMultipartFormDataStreamProvider(root);
                // Read the form data and return an async task.
                await Request.Content.ReadAsMultipartAsync(provider);

                string jsonData = provider.FormData.GetValues("Data")[0];                
                List<string> deletefiles = new List<string>();

                foreach (var file in provider.FileData)
                {
                    FileInfo fileInfo = new FileInfo(file.LocalFileName);
                    //Process File
                }
                provider.FileData.Clear();
                foreach (string deletefile in deletefiles)
                {
                    try
                    {
                        File.Delete(deletefile);
                    }
                    catch (Exception ex)
                    {
                        string error = ex.InnerException.Message;
                    }
                }

                object x = new { data = "ok"};
                return JObject.FromObject(x);

            }           
            catch (Exception ex)
            {
                // string Mensaje = LCuenta.LogError(null, ex, System.Reflection.MethodBase.GetCurrentMethod().Name);
                var error = new { error = ex.Message };
                return JObject.FromObject(error);
            }
        }


        #endregion
    }

    public class CustomMultipartFormDataStreamProvider : MultipartFormDataStreamProvider
    {
        public CustomMultipartFormDataStreamProvider(string path) : base(path) { }

        public override string GetLocalFileName(HttpContentHeaders headers)
        {
            return headers.ContentDisposition.FileName.Replace("\"", string.Empty);
        }
    }

}

我已经将此代码用于另一个应用程序,但在这种情况下,在执行JavaScript方法保存后,完整的页面重新加载,如果文件很小,则调用没有文件,只有数据y不重新加载,页面html使用mvc在asp web视图上,但只是一个容器,所有代码都在javascript上。
谢谢!

k10s72fa

k10s72fa1#

在按钮上单击使用preventDefault Ex

$("#buttonID").click(function(event){
    event.preventDefault();
});
56lgkhnf

56lgkhnf2#

这是一个visual studio配置-必须禁用文件更改时的重新加载页面

相关问题