我有一个VB ASP.net页面,允许用户上传,裁剪和保存图像,这在对话框中很明显,所以我不想刷新页面。所以,我正在尝试使用Ajax而不确定它是否可行。
有没有办法让我的代码使用?如果没有,是否有一个简单的解决方案?
注意:我测试了所有这些ASP代码并且在没有Ajax的情况下工作正常
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
因为我无法访问flImg Image字段,所以试图从Ajax发送变量,这对我不起作用,控制台返回500(内部服务器错误)
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
$(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");
}
});
}
});
});
然后尝试不使用此函数在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
答案 0 :(得分:0)
请使用以下链接下载ajax文件uplod脚本。
http://www.phpletter.com/DOWNLOAD/
然后你的代码应该如下所示。
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:
<%@ 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
答案 1 :(得分:0)
您可以按如下方式编写WebMethod(在C#中)
[WebMethod]
public string UploadFile()
{
var httpPostedFile = HttpContext.Current.Request.Files["UploadedImage"];
//Your logic to save httpPostedFile
}
}
在页面上,您可以使用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>
请记住,它可能无法在某些版本的IE上运行,否则它可以在Chrome和Firefox中顺利运行。