I need to send a file that I receive in 'testFile1' to 'testFile2'. I don't know if the stream I am creating is the right way to do it or if I have to retrieve the file on 'testFile2' in another way. Any help?
<HttpPost>
<Route("testFile1")>
Function postTestFile1() As IHttpActionResult
Try
Dim files = HttpContext.Current.Request.Files
If files.Count = 0 Then Throw New Exception("No file")
Dim file = files(0)
Dim req As HttpWebRequest = WebRequest.Create("http://localhost:9000/api/test/testFile2")
req.Method = "POST"
req.ContentType = "multipart/form-data"
req.ContentLength = file.ContentLength
Dim stream = req.GetRequestStream
Dim fileData As Byte()
Using BinaryReader As New BinaryReader(file.InputStream, Encoding.UTF8)
fileData = BinaryReader.ReadBytes(file.ContentLength)
End Using
stream.Write(fileData, 0, fileData.Length)
Dim response As WebResponse = req.GetResponse
Catch ex As Exception
Return InternalServerError()
End Try
End Function
<HttpPost>
<Route("testFile2")>
Function postTestFile2() As IHttpActionResult
Try
Dim files = HttpContext.Current.Request.Files
Dim requestStream = HttpContext.Current.Request.InputStream
If files.Count = 0 Then Throw New Exception("No file")
Dim file = files(0)
'Do the necessary with the file
Return Ok()
Catch ex As Exception
Return InternalServerError()
End Try
End Function
Related
i am try send raw data into PUT method , but i am getting error as "The remote server returned an error: (502) Bad Gateway"
But same data i try to use in Postman Agent, its working.
What i tried
Private Function SendRequest(uri As Uri, jsonDataBytes As Byte(), contentType As String, method As String) As String
Dim req As WebRequest = WebRequest.Create(uri)
req.ContentType = contentType
req.Method = method
req.ContentLength = jsonDataBytes.Length
req.Headers.Add("x-api-key:xxxxxY0tZN55jbXnY05Oxxxxx")
Dim stream = req.GetRequestStream()
stream.Write(jsonDataBytes, 0, jsonDataBytes.Length)
stream.Close()
Dim response = req.GetResponse().GetResponseStream()
Dim reader As New StreamReader(response)
Dim res = reader.ReadToEnd()
reader.Close()
response.Close()
Return res
End Function
Calling function
Dim postdata As String = "[{barcod:A0000041},{barcode:A0000113}]"
Dim data = Encoding.UTF8.GetBytes(postdata)
Dim Uri As New Uri("https://sample.com/xxxxx/xxxxx?funcName=UpdateBaarcode")
Dim result_post = SendRequest(Uri, data, "text/plain", "PUT")
What i missing , pls reply.
Regards,
Aravind
For REST API
I use WebRequest using DirectCast.
It's been so long I can't remember why. TT
Try like the code below.
Private Function SendRequest(uri As Uri, jsonDataBytes As Byte(), contentType As String, method As String) As String
Dim req As HttpWebRequest= DirectCast(WebRequest.Create(uri), HttpWebRequest)
req.ContentType = contentType
req.Method = method
req.ContentLength = jsonDataBytes.Length
req.Headers.Add("x-api-key:xxxxxY0tZN55jbXnY05Oxxxxx")
Dim stream = req.GetRequestStream()
stream.Write(jsonDataBytes, 0, jsonDataBytes.Length)
stream.Close()
Dim response = DirectCast(req.GetResponse(), HttpWebResponse)
Dim reader As New StreamReader(response.GetResponseStream)
Dim res = reader.ReadToEnd()
reader.Close()
response.Close()
Return res
End Function
Below code fails with the generic error from the title on line where creates the response
Dim httpResponse As HttpWebResponse = CType(httpWebRequest.GetResponse(), HttpWebResponse)
Code below:
Dim URL As String = "https://www150.statcan.gc.ca/t1/wds/rest/getSeriesInfoFromVector"
Dim JsonData As String = "[{""vectorId"":""1038036698""}]"
Dim OutputFile As String = "C:\Temp\1038036698.json"
Public Sub Main()
Dim myRequest As HttpWebRequest = PostJSON(JsonData)
Dim Response As String = GetResponse(myRequest)
System.IO.File.WriteAllText(OutputFile, Response)
End Sub
Private Function PostJSON(ByVal JsonData As String) As HttpWebRequest
Dim objhttpWebRequest As HttpWebRequest
Try
Dim httpWebRequest As HttpWebRequest = CType(WebRequest.Create(URL), HttpWebRequest)
httpWebRequest.Method = "POST"
httpWebRequest.ContentType = "application/json"
httpWebRequest.MediaType = "application/json"
httpWebRequest.Accept = "application/json"
Using streamWriter As StreamWriter = New StreamWriter(httpWebRequest.GetRequestStream(), Encoding.UTF8)
streamWriter.Write(JsonData)
streamWriter.Flush()
streamWriter.Close()
End Using
objhttpWebRequest = httpWebRequest
Catch ex As Exception
' Console.WriteLine("Send Request Error[{0}]", ex.Message)
Return Nothing
End Try
Return objhttpWebRequest
End Function
Private Function GetResponse(ByVal httpWebRequest As HttpWebRequest) As String
Dim strResponse As String = "Bad Request:400"
Try
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12
'next line is where it errors out
Dim httpResponse As HttpWebResponse = CType(httpWebRequest.GetResponse(), HttpWebResponse)
Dim StreamReader As StreamReader = New StreamReader(httpResponse.GetResponseStream(), True)
'Dim StreamReader As StreamReader = New StreamReader(DirectCast(httpResponse.GetResponseStream(), String), True)
Dim result As String = StreamReader.ReadToEnd()
strResponse = result.ToString()
Catch ex As Exception
Console.WriteLine("GetResponse Error[{0}]", ex.Message)
Return ex.Message
End Try
Return strResponse
End Function
We've been using an IIS filehandler to download files that are stored in a database such as PowerPoint. Now we're trying to switch to webapi. File uploads are working fine but downloads are not.
Using the filehandler the url is like: http://localhost:57851/docmgr?id=6202 which returns a valid file with the following info from Fiddler:
Using the same code in a webapi controller having a url of: http://localhost:57851/webapi/file/GetFile?id=6202 returns a file with additional bytes added. Fiddler data:
Note the change in content-type as well even though the content-type is expressly set to "application/vnd.ms-powerpoint".
I must be missing something....
Here is the controller code:
<HttpGet>
Public Function GetFile()
Dim dbConn As New SqlConnection(DigsConnStr)
Dim dbCmd As New SqlCommand
Dim dbRdr As SqlDataReader
Dim id As String = HttpContext.Current.Request.QueryString("id")
Dim bytes As Byte()
Dim contentType As String
Dim fileName As String
Dim fileExt As String
Try
dbConn.Open()
dbCmd.Connection = dbConn
dbCmd.CommandText = "GET_FileForDownload"
dbCmd.CommandType = CommandType.StoredProcedure
dbCmd.Parameters.AddWithValue("#VirtualFileRecID", id)
dbRdr = dbCmd.ExecuteReader
dbRdr.Read()
contentType = dbRdr("ContentType")
bytes = dbRdr("FileBytes")
fileExt = dbRdr("FileExtension")
If contentType <> "" Then
fileName = dbRdr("Title") & fileExt
HttpContext.Current.Response.ContentType = contentType
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" & fileName)
HttpContext.Current.Response.BinaryWrite(bytes)
'HttpContext.Current.Response.Flush()
End If
dbConn.Close()
Catch ex As Exception
dbConn.Close()
Finally
If Not (dbConn Is Nothing) Then dbConn.Close()
End Try
End Function
WebAPI is going to wrap your response in XML (or whatever formatter you have in your webapiconfig class)
You really shouldn't access the response stream directly with WebAPI but you can return a HttpResponseMessage object with the file stream
Check this out
<HTTPGET>
Public Function GetFile(FileID as Integer) As HttpResponseMessage
Dim path = "C:\Temp\test.exe"
Dim result As New HttpResponseMessage(HttpStatusCode.OK)
Dim stream = New FileStream(path, FileMode.Open)
result.Content = New StreamContent(stream)
result.Content.Headers.ContentType = New MediaTypeHeaderValue("application/octet-stream")
Return result
End Function
Then you should really access it like this: http://localhost:57851/docmgr/6202
I'm trying to create a function to download a zip file made available from a REST WebService with a client that calls the Web Service(both written in VB.Net).
WebService side I have the following code:
Public Function DownloadZipFile(filename As String) As Stream Implements ILiveUpdateWS.DownloadZipFile
WebOperationContext.Current.OutgoingResponse.ContentType = "application/txt"
Dim f As New FileStream(DESTINATION_PATH_ZIP_FILE + "Upgrade_Package.zip",FileMode.Open)
Dim length As Integer = CType(f.Length, Integer)
WebOperationContext.Current.OutgoingResponse.ContentLength = length
Dim buffer As Byte() = New Byte(length) {}
Dim sum As Integer = 0
Dim count As Integer
While ((count = f.Read(buffer, sum, length - sum)) > 0)
sum += count
End While
f.Close()
Dim mimeType = ""
WebOperationContext.Current.OutgoingResponse.ContentType = mimeType
Return New MemoryStream(buffer)
End Function
Client side I have the following code:
sUri = "http://localhost:35299/LiveUpdateWS/Download?" & "piv"
....
Dim req As HttpWebRequest = WebRequest.Create(sUri.ToString())
req.Method = "GET"
req.KeepAlive = False
Dim response As HttpWebResponse = req.GetResponse()
Dim resp As Net.HttpWebResponse = DirectCast(req.GetResponse(), Net.HttpWebResponse)
Dim stIn As IO.StreamReader = New IO.StreamReader(response.GetResponseStream())
Response has ContentLenght = 242699, so seems to receive the stream, but StIn seems to be empty. What is the best solution to solve the problem?
I think you've forgot to read from the StreamReader to the file.
Dim inSaveFile As String = "C:\stream\test.doc"
If Dir(inSaveFile) <> vbNullString Then
Kill(inSaveFile)
End If
Dim swFile As System.IO.StreamWriter
Dim fs As System.IO.FileStream = System.IO.File.Open(inSaveFile, System.IO.FileMode.CreateNew, System.IO.FileAccess.Write)
swFile = New System.IO.StreamWriter(fs, System.Text.Encoding.Default)
Dim response1 As System.Net.HttpWebResponse = req.GetResponse()
Dim resp As Net.HttpWebResponse = DirectCast(req.GetResponse(), Net.HttpWebResponse)
Dim stIn As IO.StreamReader = New IO.StreamReader(response1.GetResponseStream(), encoding:=System.Text.Encoding.Default)
swFile.WriteLine(stIn.ReadToEnd)
swFile.Close()
fs.Close()
I want to download all file that located on FTP site. I break into 2 operations. First is to get the list of all files in the directory. Then I proceed to second which download each file. But unfortunately, the downloaded file is corrupt. Worst over, it affect the file on FTP folder. Both folder contains corrupt file. From a viewing thumbnails image to default image thumbnails. How this happen and to overcome this? Below are my code; full code class. I provide as reference and guide to do a correct way :)
Private strTargetPath As String
Private strDestPath As String
Private Sub frmLoader_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Try
objSQL = New clsSQL
If objSQL.SQLGetAllData Then 'Get data from SQL and insert into an arraylist
strTargetPath = "ftp://192.168.1.120/image/"
strDestPath = "D:\Application\FTPImg\"
ListFileFromFTP()
End If
Catch ex As Exception
strErrMsg = "Oops! Something is wrong with loading login form."
MessageBox.Show(strErrMsg & vbCrLf & "ExMsg: " & ex.Message, "Error message!", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End Sub
Private Sub ListFileFromFTP()
Dim arrFile As ArrayList
Dim strPath As String
Try
Dim reqFTP As FtpWebRequest
reqFTP = FtpWebRequest.Create(New Uri(strTargetPath))
reqFTP.UseBinary = True
reqFTP.Credentials = New NetworkCredential("user", "user123")
reqFTP.Method = WebRequestMethods.Ftp.ListDirectory
reqFTP.Proxy = Nothing
reqFTP.KeepAlive = False
reqFTP.UsePassive = False
Dim response As FtpWebResponse = DirectCast(reqFTP.GetResponse(), FtpWebResponse)
Dim sr As StreamReader
sr = New StreamReader(reqFTP.GetResponse().GetResponseStream())
Dim FileListing As String = sr.ReadLine
arrFile = New ArrayList
While FileListing <> Nothing
strPath = strTargetPath & FileListing
arrFile.Add(strPath)
FileListing = sr.ReadLine
End While
sr.Close()
sr = Nothing
reqFTP = Nothing
response.Close()
For i = 0 To (arrFile.Count - 1)
DownloadImage(arrFile.Item(i))
Next
Catch ex As Exception
strErrMsg = "Oops! Something is wrong with ListFileFromFTP."
MessageBox.Show(strErrMsg & vbCrLf & "ExMsg: " & ex.Message, "Error message!", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End Sub
Public Function DownloadImage(ByVal strName As String) As String
Dim ftp_request As FtpWebRequest = Nothing
Dim ftpStream As Stream = Nothing
Dim strOldName As String
Dim strNewName As String
Dim withoutextension As String
Dim extension As String
Try
strOldName = strTargetPath & strName
withoutextension = Path.GetFileNameWithoutExtension(strOldName)
extension = Path.GetExtension(strOldName)
strNewName = strDestPath & withoutextension & extension
ftp_request = CType(System.Net.FtpWebRequest.Create(strName), System.Net.FtpWebRequest)
ftp_request.Method = System.Net.WebRequestMethods.Ftp.UploadFile
ftp_request.Credentials = New System.Net.NetworkCredential("user", "user123")
ftp_request.UseBinary = True
ftp_request.KeepAlive = False
ftp_request.Proxy = Nothing
Dim response As FtpWebResponse = DirectCast(ftp_request.GetResponse(), FtpWebResponse)
Dim responseStream As IO.Stream = response.GetResponseStream
Dim fs As New IO.FileStream(strNewName, IO.FileMode.Create)
Dim buffer(2047) As Byte
Dim read As Integer = 0
Do
read = responseStream.Read(buffer, 0, buffer.Length)
fs.Write(buffer, 0, read)
Loop Until read = 0
responseStream.Close()
fs.Flush()
fs.Close()
responseStream.Close()
response.Close()
Catch ex As WebException
Dim response As FtpWebResponse = ex.Response
If response.StatusCode = FtpStatusCode.ActionNotTakenFileUnavailable Then
MsgBox(response.StatusDescription)
Return String.Empty
Else
MsgBox(response.StatusDescription)
End If
End Try
End Function
For download file, this is the right code that succeed:
Private Sub Download(ByVal strFTPPath As String)
Dim reqFTP As FtpWebRequest = Nothing
Dim ftpStream As Stream = Nothing
Try
Dim outputStream As New FileStream(strDestPath & strImgName, FileMode.Create)
reqFTP = DirectCast(FtpWebRequest.Create(New Uri(strFTPPath)), FtpWebRequest)
reqFTP.Method = WebRequestMethods.Ftp.DownloadFile
reqFTP.UseBinary = True
reqFTP.Credentials = New NetworkCredential("user", "user123")
Dim response As FtpWebResponse = DirectCast(reqFTP.GetResponse(), FtpWebResponse)
ftpStream = response.GetResponseStream()
Dim cl As Long = response.ContentLength
Dim bufferSize As Integer = 2048
Dim readCount As Integer
Dim buffer As Byte() = New Byte(bufferSize - 1) {}
readCount = ftpStream.Read(buffer, 0, bufferSize)
While readCount > 0
outputStream.Write(buffer, 0, readCount)
readCount = ftpStream.Read(buffer, 0, bufferSize)
End While
ftpStream.Close()
outputStream.Close()
response.Close()
Catch ex As Exception
If ftpStream IsNot Nothing Then
ftpStream.Close()
ftpStream.Dispose()
End If
Throw New Exception(ex.Message.ToString())
End Try
End Sub
There is something strange in your code. You are closing the responseStream twice.
And you are using ftp request method uploadFile. But then downloading it.
Instead of using the ftp stuff use this instead. Its much more simple and your outsourcing the buffers and streams to microsoft, which should be less buggy than us.
Dim webClient = new WebClient()
webClient.Credentials = new NetworkCredential("user", "user123")
dim response = webClient.UploadFile("ftp://MyFtpAddress","c:\myfile.jpg")
dim sResponse = System.Text.Encoding.Default.GetString(response)