【问题标题】:How can I save images in a folder with javascript? ASP.NET如何使用 javascript 将图像保存在文件夹中? ASP.NET
【发布时间】:2019-09-21 12:05:33
【问题描述】:

使用asp.net中的fileupload,如何将图像保存在文件夹中,然后调用并显示它?我可以在 web 方法中使用 ajax、jquery 或 javascript 吗?

<asp:FileUpload CssClass="image" ID="fileUpload" runat="server" />

我在 c# 中有这些方法,但我在 javascript 中需要它。

 private void SaveFile(HttpPostedFile file)
        {
            string rut = Server.MapPath("~/temp");

            if (!Directory.Exists(rut))
            {
                Directory.CreateDirectory(rut);
            }

            string imgff= String.Format("{0}\\{1}", rut, file.FileName);

            if (File.Exists(imgff))
            {
                ClientScript.RegisterStartupScript(this.GetType(), "myalert", "Image()", true);
            }
            else
            {
                file.SaveAs(imgff);
            }
        }

用这个方法:

private void carga()
        {
            try
            {
                if (fileUpload.HasFile)
                {
                    // Se verifica que la extensión sea de un formato válido
                    string ext = fileUpload.PostedFile.FileName;
                    ext = ext.Substring(ext.LastIndexOf(".") + 1).ToLower();
                    string[] formatos =
                      new string[] { "jpg", "jpeg", "bmp", "png" };
                    if (Array.IndexOf(formatos, ext) < 0)
                    {
                        ClientScript.RegisterStartupScript(this.GetType(), "myalert", "FormatoImagen()", true);
                    }
                    else
                    {
                        GuardarArchivo(fileUpload.PostedFile);
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

【问题讨论】:

  • Javascript 是客户端您是否试图将其保存到使用网络浏览器的人的计算机上?如果是这样,请不要使用 javascript 这将不起作用,而是从服务器进行下载。

标签: javascript c# jquery ajax web-services


【解决方案1】:

您可以使用通用处理程序上传文件。使用 JQuery Ajax,您可以将文件上传到特定文件夹。在提交按钮中调用 JavaScript 函数

<input type="submit" value="Submit" onclick="return UploadFile();" />

JQuery Ajax

function UploadFile()
{
        $.ajax({
            url: "FileUploadHandler.ashx",
            type: "POST",
            data: data,
            contentType: false,
            async: false,
            processData: false,
            success: function (result) {
               // Process the result
            },
            error: function (err) {
                alert(err.statusText);
            }
        });
}

FileUploadHandler.ashx.cs

public class FileUploadHandler : IHttpHandler
{

    public void ProcessRequest(HttpContext context)
    {
        if (context.Request.Files.Count > 0)
        {
            HttpFileCollection files = context.Request.Files;
            for (int i = 0; i < files.Count; i++)
            {
                HttpPostedFile file = files[i];
                string extention = System.IO.Path.GetExtension(file.FileName);
                string fileName = file.FileName.Replace(extention, "") + Guid.NewGuid() + extention;
                string fname = context.Server.MapPath("~/FolderName/" + fileName);
                file.SaveAs(fname);
                context.Response.ContentType = "text/plain";
                context.Response.Write(fileName);
            }
        }
    }
}

更多信息请查看link

【讨论】:

    【解决方案2】:

    你可以这样实现,并将文件保存在文件夹中

     if (file != null)
            {
                if (file != null && file.ContentLength > 0)
                {
                    string dirUrl = "~/Uploads/";
    
                    string dirPath = Server.MapPath(dirUrl);
    
                    if (!Directory.Exists(dirPath))
                    {
                        Directory.CreateDirectory(dirPath);
                    }
                    string fileUrl = dirUrl + "/" + Path.GetFileName(file.FileName);
                    file.SaveAs(Server.MapPath(fileUrl));
                }
            }
    

    现在从文件夹或数据库中检索文件

    if (Directory.Exists(Server.MapPath("~/Uploads/" + model.id+ "/")))
                    {
                        model.Image= Directory.EnumerateFiles(Server.MapPath("~/Uploads/" + model.id + "/"))
                         .Select(fn => "~/Uploads/" + model.id + "/" + Path.GetFileName(fn));
    
                        for(int i = 0; i < model.Image.Count();i++)
                        {
    
                        }                      
                    }
    

    像这样使用ajax预览文件

    if (file.type)
                                if (regeximage.test(file.name.toLowerCase())) {
                                    var fileReader = new FileReader();
                                    fileReader.onload = function (e) {
                                        var file = e.target;
                                        $("<span class=\"pip\">" +
                                          "<div id=\"divimageId\">" + "<image  id=\"imageid\"   class=\"imageThumb\" frameborder=\'0\' src=\"" + e.target.result + "\" title=\"" + file.name + "\"></image>" + "</div>" +
                                          "<br/><span class=\"remove\">Remove file</span>" +
                                          "</span>").insertAfter("#divimageupload");
                                        $(".remove").click(function () {
                                            $(this).parent(".pip").remove();
                                            $("#divimageupload").val('');
                                        });
                                    }
    
                                    fileReader.readAsDataURL(file);
    
                                }
    

    【讨论】:

      猜你喜欢
      • 2017-12-25
      • 2013-06-23
      • 1970-01-01
      • 1970-01-01
      • 2018-05-26
      • 2018-01-29
      • 1970-01-01
      • 2021-08-12
      • 2020-06-19
      相关资源
      最近更新 更多