vb.net 使用 Ajax 和 ASP.NET 无需刷新即可将图像上传并保存到服务器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22432094/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Upload and save image to server without refresh using Ajax and ASP.NET
提问by hsobhy
I have a VB ASP.net page that allow user to upload, crop and save the image and this hapens in a dialog so I don't want to refreshthe page. So, I'm trying to use Ajax and not sure if it's possible.
我有一个 VB ASP.net 页面,允许用户上传、裁剪和保存图像,这发生在对话框中,所以我不想刷新页面。所以,我正在尝试使用 Ajax,但不确定是否可行。
Is there a way to let this work using my code? and if not is there a simple solution?
有没有办法让这个工作使用我的代码?如果没有,是否有一个简单的解决方案?
Note:I tested all these ASP codes and worked fine without Ajax
注意:我测试了所有这些 ASP 代码并且在没有 Ajax 的情况下运行良好
The regular upload is like:
常规上传是这样的:
Private Sub btnUpoadToCrop_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnUpoadToCrop.Click
Dim objUpload As New Upload
objUpload.MaxLength = 4000000
'''' Upload Image File
If objUpload.FileFieldLength(flImg) <> 0 Then
Dim flImg As HttpPostedFile = Request.Files(0)
Dim oFolder As String = "\media\temp-uploads\"
Dim strName As String = System.IO.Path.GetFileName(flImg.FileName).Replace(" " & "%20", "_").ToString
Dim oFile As String = oFolder + strName
'''' Save Original Photo
flImg.SaveAs(HttpContext.Current.Server.MapPath(oFile))
End If
End Sub
TRY AJAX
试试 AJAX
And because I couldn't access the flImg Image filed so tried to send variables from Ajax which didn't work with me and the console returning 500 (Internal Server Error)
并且因为我无法访问提交的 flImg 图像,所以尝试从 Ajax 发送变量,这对我不起作用并且控制台返回 500(内部服务器错误)
VB.NET
网络
Public Shared Function UploadSource(ByVal src As String, ByVal strName As String, ByVal ext As String) As String
'''' Upload Image File
Dim filesCollection As HttpFileCollection = HttpContext.Current.Request.Files
Dim fileName = filesCollection(0)
Dim Name As String = System.IO.Path.GetFileName(fileName.FileName).Replace(" " & "%20", "_").ToString
Dim oFolder As String = "\media\temp-uploads\"
Dim oFile As String = oFolder + Name
'''' Save Original Photo
fileName.SaveAs(HttpContext.Current.Server.MapPath(oFile))
End Function
jQUERY
查询
$(document).ready(function() {
// Ajax Upload
var _src, _path, _name, _ext;
$("#<%= flImg.ClientID%>").change(function () {
//console.dir(this.files[0]);
var val = $(this).val();
if (val != "") {
_src = val;
_name = _src.substr(0, _src.lastIndexOf('.'));
_ext = _src.split('.').pop();
_ext = _ext.toLowerCase();
alert(_ext);
}
else {
_src = "";
}
}).trigger('change');
$(document).on("click", "#UploadSource", function () {
if (_src != "") {
alert(_name);
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
url: '/ImgCropper.aspx/UploadSource',
// *** I have set values for variables for test
data: "{'src':'" + "xyz.jpg" + "','name':'" + "xyz"+ "','ext':'" + "jpg" + "'}",
async: false,
success: function (response) {
},
error: function () {
alert("some problem in saving data");
}
});
}
});
});
Then tried without sending variables in Ajax data with this function and with no hope still:
然后尝试不使用此函数在 Ajax 数据中发送变量,但仍然没有希望:
Public Shared Function UploadSource() As String
'''' Upload Image File
Dim filesCollection As HttpFileCollection = HttpContext.Current.Request.Files
Dim fileName = filesCollection(0)
Dim Name As String = System.IO.Path.GetFileName(fileName.FileName).Replace(" " & "%20", "_").ToString
Dim oFolder As String = "\media\temp-uploads\"
Dim oFile As String = oFolder + Name
'''' Save Original Photo
fileName.SaveAs(HttpContext.Current.Server.MapPath(oFile))
End Function
回答by RGS
Please download ajax file uplod script by using below link.
请使用以下链接下载ajax文件uplod脚本。
http://www.phpletter.com/DOWNLOAD/
http://www.phpletter.com/DOWNLOAD/
Then your code should be like below.
那么你的代码应该如下所示。
Html:
网址:
<input type="file" id="fileupload" name="upload"/>
<asp:LinkButton ID="btnSave" runat="server" Text="Save" Width="52px" OnClientClick="UploadFile();" />
Jquery:
查询:
$(document).ready(function () {
function UploadFile() {
var fileName = $('#fileupload').val().replace(/.*(\/|\)/, '');
if (fileName != "") {
$.ajaxFileUpload({ url: 'AjaxFileUploader.ashx',
secureuri: false,
fileElementId: 'fileupload',
dataType: 'json',
success: function (data, status) {
if (typeof (data.error) != 'undefined') {
if (data.error != '') {
alert(data.error);
} else {
alert('Success')
}
}
},
error: function (data, status, e) {
alert(e);
}
}
)
}
}
});
AjaxFileUploader.ashx:
AjaxFileUploader.ashx:
<%@ WebHandler Language="VB" Class="AjaxFileUploader" %>
Imports System.Collections.Generic
Imports System.Linq
Imports System.Web
Imports System.IO
Imports System.Text.RegularExpressions
Imports System.Text
Public Class AjaxFileUploader
Implements IHttpHandler
Implements System.Web.SessionState.IRequiresSessionState
Public Sub ProcessRequest(context As HttpContext)
If context.Request.Files.Count > 0 Then
Dim path__1 As String = context.Server.MapPath("~/Uploads")
If Not Directory.Exists(path__1) Then
Directory.CreateDirectory(path__1)
End If
Dim file = context.Request.Files(0)
Dim fileName As String
If HttpContext.Current.Request.Browser.Browser.ToUpper() = "IE" Then
Dim files As String() = file.FileName.Split(New Char() {"\"C})
fileName = files(files.Length - 1)
Else
fileName = file.FileName
End If
Dim newFile As String = Guid.NewGuid().ToString()
Dim fInfo As New FileInfo(fileName)
newFile = String.Format("{0}{1}", newFile, fInfo.Extension)
Dim strFileName As String = newFilename
fileName = Path.Combine(path__1, newFile)
file.SaveAs(fileName)
Dim msg As String = "{"
msg += String.Format("error:'{0}'," & vbLf, String.Empty)
msg += String.Format("msg:'{0}'" & vbLf, strFileName)
msg += "}"
context.Response.Write(msg)
End If
End Sub
Public ReadOnly Property IsReusable() As Boolean
Get
Return True
End Get
End Property
End Class
回答by AbdulRahman Ansari
You can write WebMethod as following(its in C#)
您可以编写 WebMethod 如下(它在 C# 中)
[WebMethod]
public string UploadFile()
{
var httpPostedFile = HttpContext.Current.Request.Files["UploadedImage"];
//Your logic to save httpPostedFile
}
}
And on the page you can send file using jQuery as following,
在页面上,您可以使用 jQuery 发送文件,如下所示,
<html>
<div>
Select File to Upload:
<input id="fileUpload" type="file" />
<input id="btnUploadFile" type="button" value="Upload File" /></div>
<script type="text/javascript">
$('#btnUploadFile').on('click', function () {
$('#<%=hdnFileName.ClientID %>').val('');
if (typeof FormData == "undefined") {
alert("Please Use Latest Version Of Google Chrome Or Mozilla Firefox To Upload Documents");
return false;
}
var data = new FormData();
var files = $("#fileUpload").get(0).files;
// Add the uploaded image content to the form data collection
if (files.length > 0) {
data.append("UploadedImage", files[0]);
}
else{
alert('Please Select File');
return;
}
var ajaxRequest = $.ajax({
type: "POST",
url: "http://localhost/WebSite/WebPage.aspx/UploadFiles",
contentType: false,
processData: false,
data: data
});
ajaxRequest.done(function (data) {
console.log(data);
alert("done");
});
ajaxRequest.error(function (xhr, status) {
console.log(xhr);
console.log(status);
alert(status);
});
});
</script>
</html>
Remember, it may not work on some versions of IE, otherwise it works in Chrome and Firefox smoothly.
请记住,它可能无法在某些版本的 IE 上运行,否则在 Chrome 和 Firefox 中可以顺利运行。

