在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;
}
}
您可以使用通用处理程序上传文件。使用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);
}