繁体   English   中英

如何使用javascript将图像保存在文件夹中? ASP.NET

[英]How can I save images in a folder with javascript? ASP.NET

使用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;
            }
        }

您可以使用Generic Handler上传文件。 使用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);
            }
        }
    }
}

有关更多信息,请查看此链接

您可以通过这种方式实现,并将文件保存在文件夹中

 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);

                            }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM