【发布时间】:2016-08-19 16:13:24
【问题描述】:
我正在尝试在网络表单中上传带有 ajax 和 vb.net 的文件。我目前正在从 ajax 获得成功响应,但我实际上从未在后端遇到断点,也没有上传任何内容或停止代码执行。这是我第一次尝试这个,所以我不确定如何专门处理后端,我在网上找到的所有东西都不符合我的确切规格。该文件需要作为 varbinary 直接上传到 db 列中。几乎所有文件都小于 256kb,所以我决定不将它们存储在文件系统中。
<input class="pull-left" type="file" id="fileToUpload"/>
<button type="button" class="btn btn-primary" data-action="uploadDoc">Upload</button>
uploadButton.on("click", function () {
var form = new FormData();
var inputFile = document.getElementById("fileToUpload");
form.append("file", inputFile.files[0]);
alert(inputFile.files.length);
$.ajax({
url: '../secure/shipments.aspx/UploadFile',
data: form,
processData: false,
contentType: false,
type: 'POST',
success: function (data) {
alert(data);
},
error: function (xhr, textStatus, errorThrown) {
alert("There was an error uploading the file. " + xhr.status + ': ' + errorThrown);
},
cache: false
});
});
<System.Web.Services.WebMethod()>
Public Shared Sub UploadFile()
Try
Dim file As HttpPostedFile = HttpContext.Current.Request.Files("file")
Dim fname As String = Path.GetFileName(file.FileName)
Dim ftype As String = file.ContentType
Dim sDatasource As String = String.Empty
Dim inputArray(flen) As Byte
Dim myStream As System.IO.Stream
If (Current.Request.Files.Count > 1) Then
file = HttpContext.Current.Request.Files("file")
fname = Path.GetFileName(file.FileName)
ftype = file.ContentType
flen = file.ContentLength
myStream = file.InputStream
'read the file into the byte array
myStream.Read(inputArray, 0, flen)
End If
If Not HttpContext.Current.Session.Contents("datasource") Is Nothing Then sDatasource = HttpContext.Current.Session.Contents("datasource").ToString()
Using con As New SqlConnection(sDatasource)
Using cmd As New SqlCommand
cmd.CommandText = "test_insertDoc"
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.AddWithValue("referenceno", 0)
cmd.Parameters.AddWithValue("doctype", ftype)
cmd.Parameters.AddWithValue("line", 0)
cmd.Parameters.Add("uploadedfile", SqlDbType.VarBinary, -1).Value = inputArray
cmd.Parameters.AddWithValue("customer", 0)
cmd.Parameters.AddWithValue("warehouse", 0)
cmd.Connection = con
con.Open()
cmd.ExecuteNonQuery()
con.Close()
cmd.Dispose()
End Using
End Using
Catch ex As Exception
End Try
End Sub
【问题讨论】:
标签: jquery asp.net ajax vb.net webforms