簡體   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