How to upload image with NicEdit and classic asp - asp-classic

I would like to use nicedit image upload with classic asp. By default Nicedit uploads images to ImageShack, but I would like to send images to my server. However I'm having trouble to adapt some features of the original PHP script to classic asp. I found this script that uploads the image and returns the image info in javascript format and generates a progress bar.
<script>
try{
top.nicUploadButton.statusCb({'done':1,'url':'$link','width':30});
}
catch(e) {
alert(e.message);
}
</script>
PHP has built-in functions that provide a progress bar and I have difficulties setting up a progress bar in vbscript.
Could someone guide me on what should be implemented so that the basic functions of this script remain in the asp version? Thanks.
==UPDATE==
I made the upload script that is working well, but I need help to make the progress bar. I usually use the jQuery progress bar inside a loop but would like to help in order to make it work during this upload process.
<%
Server.ScriptTimeout = 26000
UplMaxSize = 1048576
sExtL = "jpg,jpeg,png,gif,bmp"
Set Upload = Server.CreateObject("Persits.Upload")
Upload.OverwriteFiles = True
Upload.SetMaxSize UplMaxSize, True
nCount = Upload.Save
If nCount > 0 Then
Set File = Upload.Files(1)
sFileName = File.FileName
sWidth = File.ImageWidth
If Err.Number = 8 Then
Set uplresult = jsObject()
uplresult("error") = "O tamanho do arquivo excedeu o limite!"
uplresult.Flush ' estampa json
Response.End()
End If
If Not File Is Nothing Then
' Save the file to the file system
sPath = Server.MapPath(".\public\upimages")
Set oFSO = Server.CreateObject("Scripting.FileSystemObject")
sExt = oFSO.GetExtensionName(sPath & sFileName)
If Not (InStr(sExtL,sExt) > 0) Then
Set uplresult = jsObject()
uplresult("error") = "Extensão de arquivo inválida!"
uplresult.Flush ' estampa json
Response.End()
End If
File.SaveAs sPath & "\" & sFileName
Response.Write("<script>try {top.nicUploadButton.statusCb({'done':1,'url':'/blog/public/upimages/" & sFileName & "','width':" & sWidth & "});} catch(e) {alert(e.message);}</script>")
End If
End If
%>

Related

VB.NET FTP Picture Upload Error [duplicate]

This question already has answers here:
Zip file is getting corrupted after downloading from server in C#
(3 answers)
Closed 4 years ago.
I am trying to allow authenticated users to upload pictures to the server through FTP. The code works for the most part. The part that doesn't is that there is an issue in uploading the file. I have tried to upload a few different pictures and all of them are larger on the server and therefore, not properly constructed.
One picture I tried is 4.56MB on my computer and 8.24MB on the server. When I load the picture in Photo, it states "We can't open this file." The page location is at http://troop7bhac.com/pages/slideshowedit.aspx. The following is the VB.NET code behind the upload:
Sub uploadFile_Click(sender As Object, e As EventArgs)
lblUploadErrors.InnerHtml = ""
If (lstSlideshowChoose.SelectedValue = "") Then
lblUploadErrors.InnerHtml = "<p>A slideshow must be selected.</p>"
Else
If (FileUpload1.HasFile) Then
Dim nameList() As String
Dim successList() As String
Dim i As Integer = 0
For Each file As HttpPostedFile In FileUpload1.PostedFiles
Dim fileBytes() As Byte = Nothing
Dim fileName As String = Path.GetFileName(file.FileName)
Dim photoRE As New Regex("^[A-z0-9 _]{1,}\.jpg|JPG|jpeg|JPEG|png|PNG+$")
Dim photoSuccess As Boolean = photoRE.Match(fileName).Success
ReDim Preserve nameList(i)
ReDim Preserve successList(i)
If (photoSuccess = True) Then
Using fileStream As New StreamReader(file.InputStream)
fileBytes = Encoding.UTF8.GetBytes(fileStream.ReadToEnd())
fileStream.Close()
End Using
Try
Dim request As FtpWebRequest = DirectCast(WebRequest.Create(ftpPath & lstSlideshowChoose.SelectedValue & "/" & fileName), FtpWebRequest)
request.Method = WebRequestMethods.Ftp.UploadFile
request.Credentials = New NetworkCredential(ftpUser, ftpPass)
Using uploadStream As Stream = request.GetRequestStream()
uploadStream.Write(fileBytes, 0, fileBytes.Length)
uploadStream.Close()
End Using
Dim response As FtpWebResponse = DirectCast(request.GetResponse(), FtpWebResponse)
response.Close()
successList(i) = "Success "
Catch ex As Exception
successList(i) = "Failed "
End Try
Else
successList(i) = "Failed "
End If
nameList(i) = fileName
i += 1
Next
For x As Integer = 0 To nameList.Count - 1
lblUploadErrors.InnerHtml += "<p>" & successList(x) & nameList(x) & "</p>"
Next
Else
lblUploadErrors.InnerHtml = "<p>You have not selected a picture to upload.</p>"
End If
End If
End Sub
The files are obtained through an ASP.NET FileUpload control. The control has been set to allow multiple files at once.
Any help to figure out why the pictures are not uploading properly would be greatly appreciated.
EDIT: I tried Martin Prikryl's possible duplicate solution. Had to change it from C# to VB.NET. It failed. I tried David Sdot's solution and it also failed. Both solutions returned the same errors.
If the page was ran on my local machine, it returned "C:\Program Files (x86)\IIS Express\PictureName.JPG." If the page was ran on the server, it returned "C:\Windows\SysWOW64\inetsrv\PictureName.JPG." Both errors are of the System.IO.FileNotFoundException class.
Your Problem is here:
Using fileStream As New StreamReader(file.InputStream)
fileBytes = Encoding.UTF8.GetBytes(fileStream.ReadToEnd())
fileStream.Close()
Using
Your image is read as text. From this text you get the bytes UTF8 byte values, thats why your image is nearly twice the size when uplaoded. You need the bytes from the image, without converting them to something else.
fileBytes = File.ReadAllBytes(file.FileName)

Is it possible to copy files from a UNC source to a webDav destination with a script?

I work in a very large, complex Intranet environment. I have run into a very unique issue that I cannot seem to resolve.
Forwarning
The technologies I mention are very outdated and that is the way is has to stay. I work in a very large enterprise and they have a ton of legacy things in place. I normally work on the modern side of things, but this got placed in my lap.
The problem:
We have a file located on our IIS 7.x server with path \serverName\shareName\wwwroot\myfile.jpg. I need to copy this file to a webDav location of a DIFFERENT web server using ASP , vbscript, or another similar web technology. For a multitude of security implications, I don't have access to the webDav UNC path, only the http: path. I am able to map this drive and access the http: location using windows explorer. I can even manually copy files, create files, and delete them. However, when I try to use a script, I get no where.
I am not great with vbscript so bare with my attempts:
Attempt 1:
Set oShell = CreateObject("WScript.Shell")
strCommand = oShell.Run("Xcopy ""sourceLocation"" ""destination location"" /S /Y", 0, True)
If strCommand <> 0 Then
MsgBox "File Copy Error: " & strCommand
Else
MsgBox "Done"
End If
Attempt 2:
<%
dim objFSOpublish
set objFSOpublish = CreateObject("Scripting.FileSystemObject")
strCurrentUNCfull = "sourcePath"
mPublishPath = "destinationPath"
objFSOpublish.CopyFile strCurrentUNCfull, mPublishPath
set objFSOpublish = nothing
%>
I have no idea if this is even possible to do without the webDav UNC path because I don't have much experience with webDav. If it is possible I have exhausted my limited knowledge in this space and need help badly. I scoured Google tirelessly trying to find a similar issue to no avail. Any and all help or direction will be greatly appreciated.
You're going to want to do something like this:
On Error Resume Next
sUrl = "YourURLHere"
sFile = "UNCPathToYourFile"
'Here we are just reading your file into an ODB
'stream so we can manipulate it
Set oStream = CreateObject("ADODB.Stream")
oStream.Mode = 3
oStream.Type = 1
oStream.Open
oStream.LoadFromFile(sFile)
'Here we are doing the upload of the oStream
'object we just created.
Set oHTTP = CreateObject("MSXML2.ServerXMLHTTP")
oHTTP.Open "POST", sUrl, False
oHTTP.SetRequestHeader "Content-Length", oStream.Size
oHTTP.Send oStream.Read(oStream.Size)
'Check for errors.
If Err = 0 Then
Wscript.Echo oHTTP.responseText
Else
Wscript.Echo "Upload Error!" & vbCrLf & Err.Description
End If
'Optionally close out our objects
oStream.Close
Set oStream = Nothing
Set oHTTP = Nothing
Here is the code I am currently using with the actual file path redacted. Let me know if you see anything that is incorrect.
The page is saved as a .ASP.
<%
sUrl = "http://server.site.com:80/subDomain/wwwroot/"
sFile = "\\server\developmentShare\wwwroot\page.htm"
'Here we are just reading your file into an ODB
'stream so we can manipulate it
Set oStream = Server.CreateObject("ADODB.Stream")
oStream.Mode = 3
oStream.Type = 1
oStream.Open
oStream.LoadFromFile(sFile)
'Here we are doing the upload of the oStream
'object we just created.
Set oHTTP = CreateObject("MSXML2.ServerXMLHTTP")
oHTTP.Open "POST", sUrl, False
oHTTP.SetRequestHeader "Content-Length", oStream.Size
oHTTP.Send oStream.Read(oStream.Size)
'Check for errors.
If Err = 0 Then
Wscript.Echo oHTTP.responseText
Else
Wscript.Echo "Upload Error!" & vbCrLf & Err.Description
End If
'Optionally close out our objects
oStream.Close
Set oStream = Nothing
Set oHTTP = Nothing
%>

Save Base64 to an image using Classic ASP

I have been trying to save a base64 file as an image from server side using classic ASP. What I want is it to autosave the file to a specific location and give it a filename, Now I am fine coding that aspect of it. However I can't get the code to save the image without first rendering on a browser. This isn't going to work for me as the script I am using will be an automatic export and have no user input.
Code follows as yet that renders in the webpage and asks the user where to save the image. Just to reiterate I need it to auto save (no user input)
base64String ="base64 code goes here - Wont add it as its huge amount of text"
Set tmpDoc = Server.CreateObject("MSXML2.DomDocument")
Set nodeB64 = tmpDoc.CreateElement("b64")
nodeB64.DataType = "bin.base64" ' stores binary as base64 string
nodeB64.Text = Mid(base64String, InStr(base64String, ",") + 1) ' append data text (all data after the comma)
vehicleAuditName= "Audit1"
With Response
.Clear
.ContentType = "image/png"
.AddHeader "Content-Disposition", "attachment; filename=" & vehicleAuditName & ".png"
.BinaryWrite nodeB64.NodeTypedValue 'get bytes and write
.end
End With
use an adodb.stream object to store the image on the server side like so:
dim bStream : set bStream = server.CreateObject("ADODB.stream")
bStream.type = adTypeBinary
call bStream.Open()
call bStream.Write( binData )
call bStream.SaveToFile( FullName, adSaveCreateOverWrite)
call bStream.close()
set bStream = nothing
The server side code that receives the base64 string is below, please note that this is code that is taken from a working system so there are variables such as carreg / auditdate that are used as unique identifiers for giving the created file a name:
function convBase64 (convVal, getCarReg, convType, AuditDate, AuditReference)
base64String = convVal
carReg = (UCase(getCarReg))
carReg = (Replace(getCarReg," ",""))
AuditDate= CDate(AuditDate)
ConvAuditDate = ((DatePart("d",AuditDate))& "_" & (DatePart("m",AuditDate)) & "_" & (DatePart("YYYY",AuditDate)))
select case convType
Case "Sig1"
FileNameSuffix = "AuditorsSignature"
Case "Sig2"
FileNameSuffix = "BodyShopSignature"
Case "Car"
FileNameSuffix = "DamageCanvas"
end select
ImageFileName = FileNameSuffix & "-" & carReg & "-" & ConvAuditDate & ".jpg"
Set tmpDoc = Server.CreateObject("MSXML2.DomDocument")
Set nodeB64 = tmpDoc.CreateElement("b64")
nodeB64.DataType = "bin.base64" ' stores binary as base64 string
nodeB64.Text = Mid(base64String, InStr(base64String, ",") + 1) ' append data text (all data after the comma)
dim bStream : set bStream = server.CreateObject("ADODB.stream")
bStream.type = 1
call bStream.Open()
call bStream.Write( nodeB64.NodeTypedValue )
call bStream.SaveToFile(Server.Mappath("NoneVehicleImages/" & AuditReference & "/" & ImageFileName), 2 )
call bStream.close()
set bStream = nothing
convBase64 = "\\iis_fdg$\AuditExport\NoneVehicleImages\" & AuditReference & "\" & ImageFileName
end function
You cannot do this due to security reasons. If web pages could randomly choose where to store files on our local systems without any user interaction, there would chaos.

asp.net + previewing an image without saving it locally

I a function belows which is being used to preview an image but that involves saving the image locally in my drive. I am using this feature in an data entry form which means if the user discards the form, I have to delete the image which I feel is not efficient. How can I go about previewing the image and only save it locally if the user saves the form. Thanks.
Protected Sub save_btn_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btn_Save.Click
If uifuVouTypeUploadfile.PostedFile IsNot Nothing Then
' Check file size (mustn’t be 0)
Dim myFile As HttpPostedFile = uifuVouTypeUploadfile.PostedFile
Dim nFileLen As Integer = myFile.ContentLength
If nFileLen = 0 Then
'rqfvVouImage.ErrorMessage = "No file was uploaded."
'rqfvVouImage.IsValid = False
Return
End If
' Check file extension (must be JPG)
If System.IO.Path.GetExtension(myFile.FileName).ToLower() <> ".jpg" AndAlso System.IO.Path.GetExtension(myFile.FileName).ToLower() <> ".gif" AndAlso System.IO.Path.GetExtension(myFile.FileName).ToLower() <> ".bmp" Then
'rqfvVouImage.ErrorMessage = "The file must have an extension of JPG or GIF"
'rqfvVouImage.IsValid = False
Return
Else
myFile.SaveAs(MapPath(System.IO.Path.GetFileName(myFile.FileName).ToLower().ToString()))
'Show the uploaded resized picture in the image control
uiimgVouImage.ImageUrl = System.IO.Path.GetFileName(myFile.FileName).ToLower().ToString()
End If
End If
End Sub
You may construct the Bitmap object of uploaded file and write it to Response stream.
Bitmap bmp = new Bitmap(uifuVouTypeUploadfile.PostedFile.InputStream);
bmp.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
Response.Flush();
Response.End();
Take a look at these posts:
How to show the selected image file without saving file in the disk before upload
Image preview before uploading using AsynFileUpload

ASP.NET - remote screenshot

I made a very very simple small app to take screenshot of the desktop and send to network share. About 10 PC's would have this app installed.
My idea is, that there will be one dashboard in ASP.NET, which simply shows those screenshots on the webpage. So far, easy stuff.
But, because I don't want to clog the network and send the screenshot every 1 minute, I would like to launch the .exe on the remote PC's by demand of ASP.NET user.
Unfortunately I haven't found any information (and I'm a complete ASP.NET n00b), how to launch remote executable IN the context of the remote PC (so I won't see screenshots of ASP server :) )
If there is no such possibility, please advise about other way to solve this.
Update after clarification:
Take a look at the situation from another angle:
Why don't you run a web server on the clients that host an asp.net page that triggers the capture. Then you can, from your root server, simply sent http requests to the clients and fetch the image.
You can try http://CassiniDev.codeplex.com - it supports external IP and hostnames.
And you may also consider simply embedding the CassiniDev-lib (a very simple example is shown here - Using CassiniDev to host ASP.Net in your application, that way you can use the web server as the reciever and the forms app can do whatever it wants on the client.
I am confident in this approach as I designed cassinidev with this as one of the primary use cases.
From asp.net you cannot. It is only HTML/JavaScript once it gets to the browser.
ActiveX is a possibility but it is quite painful and dated and limited. And painful.
The new way to do something like this is to deploy a .net Forms application or WPF app via Click Once.
You can also write a WPF Browser Application but getting the kind of permissions you would need would entail setting the site as full trust.
If a web page could launch an arbitrary .exe file on your machine, that would be a security disaster.
However, since these are your PCs, you can require them to install an ActiveX control of some kind that you could then embed in your ASP.NET page.
As others have said, there is really no way for ASP.Net to call out to the apps, but reversing the control flow should work OK...
I suppose you could have the grabber application running all the time on the users desktop, but have it make a call to a web service / file served by the server that contains an instruction for that instance of the app to grab a screenshot.
Something like...
App : Do I have to do anything? (GET /workinstruction.aspx)
Server : no. (server decides whether to request work, and return the result in (workinstruction.aspx)
App : (waits 1 minute)
App : Do I have to do anything?
Server : yes.
App : (takes screenshot and submits)
App : (waits 1 minute)
App : Do I have to do anything?
etc...
Thank you all for answering, those were interesting approaches to the subject.
Yet due to many factors I ended up with following solution:
Pseudo-service (Windows Forms with tray icon and hidden form) application on client PC's. It is serving as TCP server.
ASP.Net web app on the server, with TCP client function.
On request of the web user, web app is sending preformatted TCP 'activation' string to the chosen PC. Tray app is making a screenshot and sending it to predefined SMB share, available for web app to display.
Thanks again!
I've done this exact thing a few times for monitoring remote display systems. What I found was that using MiniCap.exe to capture image also took video (which was required on remote display systems).
I also used Cassini as described by Sky Sanders with an ASPX-page with the following code.
Then I just reference the page from an img src="http://computer/page.aspx?paramters". (Let me know if you need more info)
<%# Import NameSpace="System.IO" %>
<%# Import NameSpace="System.Drawing" %>
<%# Import NameSpace="System.Drawing.Imaging" %>
<%# Import NameSpace="System.Diagnostics" %>
<%
Response.Buffer = True
Response.BufferOutput = True
Dim CompressionLevel As Integer = 1
Dim compress As Integer = 1
If Not Request.Item("compress") Is Nothing Then
If IsNumeric(Request.Item("compress")) = True Then
CompressionLevel = CInt(Request.Item("compress"))
End If
End If
compress = CompressionLevel
' Resize requested?
Dim SizeX As Integer = 100
Dim SizeY As Integer = 75
If Not Request.Item("width") Is Nothing Then
If IsNumeric(Request.Item("width")) = True Then
SizeX = CInt(Request.Item("width"))
CompressionLevel = 10
End If
End If
If Not Request.Item("height") Is Nothing Then
If IsNumeric(Request.Item("height")) = True Then
SizeY = CInt(Request.Item("height"))
CompressionLevel = 10
End If
End If
Dim Region As String = ""
If Not Request.Item("region") Is Nothing Then
Region = Request.Item("region")
End If
Dim XS As Integer = 0
Dim YS As Integer = 0
Dim XE As Integer = 1023
Dim YE As Integer = 766
Try
If Region.IndexOf(",") > -1 Then
Dim Rec() As String = Region.Split(",")
If Rec.GetUpperBound(0) >= 3 Then
If IsNumeric(Rec(0)) Then XS = Rec(0)
If IsNumeric(Rec(1)) Then YS = Rec(1)
If IsNumeric(Rec(2)) Then XE = Rec(2)
If IsNumeric(Rec(3)) Then YE = Rec(3)
End If
End If
Catch : End Try
Dim FileType As String = "jpg"
Dim MimeType As String = "jpeg"
If Not Request.Item("filetype") Is Nothing Then
FileType = Request.Item("filetype")
MimeType = FileType
End If
If Not Request.Item("mimetype") Is Nothing Then
FileType = Request.Item("mimetype")
End If
Dim ImageFile As String = ""
Dim ImageThumbFile As String = ""
Dim ImageFolder As String = Server.MapPath("~/ScreenShots/")
If IO.Directory.Exists(ImageFolder) = False Then
IO.Directory.CreateDirectory(ImageFolder)
End If
' Delete files older than 30 minutes
For Each File As String In IO.Directory.GetFiles(ImageFolder)
Response.Write("File: " & File & "<br>")
If IO.File.GetCreationTimeUtc(File).AddMinutes(30) < Now.ToUniversalTime Then
IO.File.Delete(File)
End If
Next
' Find available filename
Dim tmpC As Integer = 0
While tmpC < 100
tmpC += 1
ImageFile = "ScreenShot_" & CStr(tmpC).PadLeft(5, "0") & "." & FileType
ImageThumbFile = "ScreenShot_" & CStr(tmpC).PadLeft(5, "0") & "_thumb." & FileType
If IO.File.Exists(ImageFolder & "\" & ImageFile) = False Then
' Found our filename
' Reserve it
Dim ios As IO.FileStream = IO.File.Create(ImageFolder & "\" & ImageFile)
ios.Close()
ios = Nothing
Exit While
End If
End While
' Run MiniCap
' " -capturedesktop" & _
Dim CMD As String = """" & Server.MapPath("/MiniCap.EXE") & """" & _
" -save """ & ImageFolder & "\" & ImageFile & """" & _
" -captureregion " & XS & " " & YS & " " & XE & " " & YE & _
" -exit" & _
" -compress " & CompressionLevel
If Not CMD Is Nothing Then
Dim myProcess As Process = New Process
Dim RouteFB As String
With myProcess
With .StartInfo
.FileName = "cmd.exe"
.UseShellExecute = False
.CreateNoWindow = True
.RedirectStandardInput = True
.RedirectStandardOutput = True
.RedirectStandardError = True
End With
.Start()
End With
Dim sIn As IO.StreamWriter = myProcess.StandardInput
sIn.AutoFlush = True
' Create stream reader/writer references
Dim sOut As IO.StreamReader = myProcess.StandardOutput
Dim sErr As IO.StreamReader = myProcess.StandardError
' Send commands
sIn.Write(CMD & System.Environment.NewLine)
sIn.Write("exit" & System.Environment.NewLine)
' Wait one second
'Threading.Thread.CurrentThread.Sleep(60000)
' Read all data
Response.Write(sOut.ReadToEnd)
' Kill process if still running
If Not myProcess.HasExited Then
myProcess.Kill()
End If
sIn.Close()
sOut.Close()
sErr.Close()
myProcess.Close()
End If
Response.Clear()
Response.ClearContent()
If Not Request.Item("width") Is Nothing Or Not Request.Item("length") Is Nothing Then
' Resize, making thumbnail in desired size
Dim b As Bitmap = Bitmap.FromFile(ImageFolder & "\" & ImageFile)
Dim thumb As Bitmap = b.GetThumbnailImage(SizeX, SizeY, Nothing, IntPtr.Zero)
' Jpeg image codec
Dim jpegCodec As ImageCodecInfo
' Get image codecs for all image formats
Dim codecs As ImageCodecInfo() = ImageCodecInfo.GetImageEncoders()
' Find the correct image codec
For i As Integer = 0 To codecs.Length - 1
If (codecs(i).MimeType = "image/" & MimeType) Then
jpegCodec = codecs(i)
Exit For
End If
Next i
Dim qualityParam As New EncoderParameter(System.Drawing.Imaging.Encoder.Quality, compress * 10)
Dim encoderParams As New EncoderParameters(1)
encoderParams.Param(0) = qualityParam
thumb.Save(ImageFolder & "\" & ImageThumbFile, jpegCodec, encoderParams)
thumb.Dispose()
b.Dispose()
' Send thumb
Response.TransmitFile(ImageFolder & "\" & ImageThumbFile)
Else
' Send normal file
Response.TransmitFile(ImageFolder & "\" & ImageFile)
End If
Response.End()
%>

Resources