I have a project to upload files to Sharepoint using REST API ( POST).
I am using vb.net and RestSharp. Code is below. this code is working.
I am able to do with the small Text file only and the file is getting properly upload into Sharepoint. But when it comes to another file format ( XLS, XLSX, PDF, JOG, Doc ..etc) with a file size greater than 1 MB file is getting uploaded with it, not in a readable format. I tried to upload a ZIP file for 55 MB it is getting Uploaded. But When I download the same uploaded file I am not able to read it.
Can anyone please help me, to get this fixed?
** I would need a solution to upload any file format for any size ( In my project I will not use any file more than 500 MB for upload. )
Below is the code is tried.
Public Sub UploadFile2()
Dim FullfileName As String = "E:\Desktop\try\FileToUpload.xlsx"
Dim NewFileName As String = "NewFile.xlsx"
Dim uploadFileUrl As String = SiteUrl + "_api/web/lists/getByTitle('Documents')/RootFolder/Files/Add(url='" + NewFileName + "', overwrite=true)"
Dim client = New RestClient(uploadFileUrl) With {
.Timeout = -1
}
Dim UploadRequest = New RestRequest(Method.POST)
UploadRequest.AddHeader("Accept", "application/json;odata=verbose")
UploadRequest.AddHeader("X-RequestDigest", DigestValue)
UploadRequest.AddHeader("Authorization", "Bearer " + AccessToken)
UploadRequest.AddHeader("Content-Type", "multipart/form-data")
UploadRequest.AlwaysMultipartFormData = True
UploadRequest.AddFile("FileName", FullfileName)
UploadResponse = client.Execute(UploadRequest)
End Sub
Looks like you need to pass the Content-Length header.
For anyone interested, this worked for me:
Public Sub UploadFile2()
Dim FullfileName As String = "E:\Desktop\try\FileToUpload.xlsx"
Dim NewFileName As String = "NewFile.xlsx"
Dim uploadFileUrl As String = SiteUrl + "_api/web/lists/getByTitle('Documents')/RootFolder/Files/Add(url='" + NewFileName + "', overwrite=true)"
Dim client = New RestClient(uploadFileUrl) With {
.Timeout = -1
}
Dim UploadRequest = New RestRequest(Method.POST)
UploadRequest.AddHeader("Accept", "application/json;odata=verbose")
UploadRequest.AddHeader("X-RequestDigest", DigestValue)
UploadRequest.AddHeader("Authorization", "Bearer " + AccessToken)
UploadRequest.AddHeader("Content-Type", "application/octet-stream")
UploadRequest.AddParameter("application/octet-stream", File.ReadAllBytes(FullfileName), ParameterType.RequestBody)
UploadResponse = client.Execute(UploadRequest)
End Sub
Related
Hi I am currently using CKEditor 5 and my problem is the image upload. The ckeditor allows me to upload an image and it displays within the CKEditor, the file is also being uploaded to a folder using a custom VB Script but i keep getting the error: Cannot upload file - filename. Then the Image disappears from ckeditor. Does anyone know what i am doing wrong? is the image URL not being passed back properly to CKEditor?
var myEditor;
ClassicEditor
.create(document.querySelector('#CKEditor1'), {
ckfinder: {
filebrowserUploadMethod: 'form',
// Upload the images to the server using the CKFinder QuickUpload command.
uploadUrl: 'Scripts/uploadVB.aspx?CKEditor=CKEditor1&CKEditorFuncNum=1&langCode=en'
}
})
.then(editor => {
console.log('Editor was initialized', editor);
myEditor = editor;
})
.catch( error => {
console.error( error );
});
<div id="CKEditor1">This is some sample content.</div>
UploadVB Page
<%# Page Language="VB" Strict="true"%>
<script src="https://cdn.ckeditor.com/ckeditor5/22.0.0/classic/ckeditor.js"></script>
<script runat="server">
Sub Page_Load(ByVal o As Object, ByVal e As EventArgs)
Response.Write(processUpload())
'processUpload()
End Sub
'https://github.com/AlfonsoML/CKEditorUploader/blob/master/uploadVB.aspx
Dim basePath As String = "C:\Users\new\Image\CN_Image"
' Step 3: Put here the Url that should be used for the upload folder (it the URL to access the folder that you have set in $basePath
' you can use a relative url "/images/", or a path including the host "http://example.com/images/"
' ALWAYS put the final slash (/)
Dim baseUrl As String = "/Image/CN_Image/"
' Done. Now test it!
' No need to modify anything below this line
'----------------------------------------------------
' ------------------------
' Input parameters: optional means that you can ignore it, and required means that you
' must use it to provide the data back to CKEditor.
' ------------------------
' Optional: instance name (might be used to adjust the server folders for example)
Dim CKEditor As String = HttpContext.Current.Request("CKEditor")
' Required: Function number as indicated by CKEditor.
Dim funcNum As String = HttpContext.Current.Request("CKEditorFuncNum")
'Dim CKEditorFuncNum As String = Context.Request("CKEditorFuncNum")
' Optional: To provide localized messages
Dim langCode As String = HttpContext.Current.Request("langCode")
' ------------------------
' Data processing
' ------------------------
Dim total As Integer
Try
total = HttpContext.Current.Request.Files.Count
Catch ex As Exception
Return sendError("Error uploading the file")
End Try
If (total = 0) Then
Return sendError("No file has been sent")
End If
If (Not System.IO.Directory.Exists(basePath)) Then
Return sendError("basePath folder doesn't exists")
End If
'Grab the file name from its fully qualified path at client
Dim theFile As HttpPostedFile = HttpContext.Current.Request.Files(0)
Dim strFileName As String = theFile.FileName
If (strFileName = "") Then
Return sendError("File name is empty")
End If
Dim sFileName As String = System.IO.Path.GetFileName(strFileName)
Dim name As String = System.IO.Path.Combine(basePath, sFileName)
theFile.SaveAs(name)
Dim url As String = baseUrl + sFileName.Replace("'", "\'")
' ------------------------
' Write output
' ------------------------
Return "<scr" + "ipt type='text/javascript'> window.parent.CKEDITOR.tools.callFunction(" + funcNum + ", '" + url + "', '')</scr" + "ipt>"
End Function
Private Function sendError(ByVal msg As String) As String
Dim funcNum As String = HttpContext.Current.Request("CKEditorFuncNum")
Return "<scr" + "ipt type='text/javascript'> window.parent.CKEDITOR.tools.callFunction(" + funcNum + ", '', '" + msg + "')</scr" + "ipt>"
End Function
</script>
I'm working on a windows forms application, using vb.net and microsoft sql server as backend. As for the reports, I'm using microsoft's rdlc, which has been quite satisfactory for me until I was struck with this distinct problem.
So, in the report I'm using external images, which are loaded through local filepaths, passed as parameters. I retrieve these paths from the database and pass it to the report. This method worked for me for a long time, until it stopped working. Now the case is, that the external images are not loading in the report (a red cross is displayed instead of the image). As far as I feel, this problem has something to do with permissions on my PC because the same code and configurations worked for me before, but I'm not able to resolve it. I have searched everywhere to no end and would definitely want assistance.
My code for the report is:
Try
With Me.ReportViewer1.LocalReport
.DataSources.Clear()
.ReportPath = Application.StartupPath & "\RptArticle.rdlc"
.EnableExternalImages = True
Dim imagepathstring As String = System.IO.Path.Combine(folder & "\ArticlePics", imagepath)
Dim imgparameter As New ReportParameter
imgparameter = New ReportParameter("ImagePath", "file://" & imagepathstring, True)
.SetParameters(imgparameter)
Dim barpathstring As String = System.IO.Path.Combine(folder & "\BarCode", barpath)
Dim barcode As New ReportParameter("Barcode", "file://" & barpathstring, True)
.SetParameters(barcode)
.DataSources.Add(New Microsoft.Reporting.WinForms.ReportDataSource("DSArticleAccessory", Accdt))
.DataSources.Add(New Microsoft.Reporting.WinForms.ReportDataSource("DSArticleSize", AccSdt))
.DataSources.Add(New Microsoft.Reporting.WinForms.ReportDataSource("DSArticleColour", AccCdt))
.DataSources.Add(New Microsoft.Reporting.WinForms.ReportDataSource("DSArticleColour", AccCdt))
.DataSources.Add(New Microsoft.Reporting.WinForms.ReportDataSource("DSArticle", dt))
End With
Me.ReportViewer1.ZoomMode = ZoomMode.PageWidth
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
Me.ReportViewer1.RefreshReport()
When I load the report, the output is:
Warning: Images with external URL references will not display if the report is published to a report server without an UnattendedExecutionAccount or the target image(s) are not enabled for anonymous access. (rsWarningFetchingExternalImages)
Warning: The value of the MIMEType property for the image ‘Image1’ is “application/octet-stream”, which is not a valid MIMEType. (rsInvalidMIMEType)
Warning: The value of the ImageData property for the image ‘Image1’ is “”, which is not a valid ImageData. (rsInvalidExternalImageProperty)
Warning: The value of the MIMEType property for the image ‘Image2’ is “application/octet-stream”, which is not a valid MIMEType. (rsInvalidMIMEType)
Warning: The value of the ImageData property for the image ‘Image2’ is “”, which is not a valid ImageData. (rsInvalidExternalImageProperty)
The thread 0x3948 has exited with code 0 (0x0).
Instead of using external images, you can pass your images as string to your report as parameters.
Convert your image to Base64 string first using this:
Public Function ImageToBase64(ByVal image As Image, ByVal format As System.Drawing.Imaging.ImageFormat) As String
Dim base64String As String = ""
Using ms As New System.IO.MemoryStream()
image.Save(ms, format)
Dim imageBytes As Byte() = ms.ToArray()
base64String = Convert.ToBase64String(imageBytes)
End Using
Return base64String
End Function
So this:
Dim imagepathstring As String = System.IO.Path.Combine(folder & "\ArticlePics", imagepath)
Dim imgparameter As New ReportParameter
imgparameter = New ReportParameter("ImagePath", "file://" & imagepathstring, True)
.SetParameters(imgparameter)
Dim barpathstring As String = System.IO.Path.Combine(folder & "\BarCode", barpath)
Dim barcode As New ReportParameter("Barcode", "file://" & barpathstring, True)
.SetParameters(barcode)
will be like this:
Dim imagepathstring As String = System.IO.Path.Combine(folder & "\ArticlePics", imagepath)
Dim imgparameter As New ReportParameter
imgparameter = New ReportParameter("ImagePath", ImageToBase64(Image.FromFile(imagepathstring),<THE IMAGE FORMAT OF YOUR IMAGE>))
.SetParameters(imgparameter)
Dim barpathstring As String = System.IO.Path.Combine(folder & "\BarCode", barpath)
Dim barcode As New ReportParameter("Barcode", ImageToBase64(Image.FromFile(barpathstring),<THE IMAGE FORMAT OF YOUR IMAGE>))
.SetParameters(barcode)
Then, in your report set the following for:
ImagePath
MIMEType = select the correct MIME type from the dropdown list
Source = Database
Value = <Expression>
and in the Expression window:
=System.Convert.FromBase64String(Parameters!ImagePath.Value)
Barcode
MIMEType = select the correct MIME type from the dropdown list
Source = Database
Value = <Expression>
=System.Convert.FromBase64String(Parameters!Barcode.Value)
I am making a media player application using AXWMPlib which has a playlist.
what i successfully able to do was saving the playlist items in a text file.
below is the code for saving:
If SavePlaylist.ShowDialog = Windows.Forms.DialogResult.OK Then
Dim writefile As New System.IO.StreamWriter(SavePlaylist.FileName)
For i = 0 To lstview.Items.Count - 2
writefile.WriteLine(Form1.main.AxWMP1.currentPlaylist.Item(i).sourceURL)
Next
writefile.Write(Form1.main.AxWMP1.currentPlaylist.Item(Form1.main.AxWMP1.currentPlaylist.count - 1).sourceURL)
writefile.Close()
End If
for loading i wrote till here:
If OpenPlaylist.ShowDialog = Windows.Forms.DialogResult.OK Then
Dim readfile As New System.IO.StreamReader(OpenPlaylist.FileName)
Dim ob As String = readfile.ReadToEnd()
Dim content() As String = OpenPlaylist.FileName.Split(Environment.NewLine)
End If
i dont know how to read the lines stored in current() and append them in current playlist.
found a solution:
If Open.ShowDialog = Windows.Forms.DialogResult.OK Then
Dim readfile As New System.IO.StreamReader(Open.FileName)
Dim ob As String = readfile.ReadToEnd()
Dim content() As String = ob.Split(Environment.NewLine)
For Each Line As String In content
Dim item As IWMPMedia = Form1.AxWMP1.newMedia(Line)
Form1.AxWMP1.currentPlaylist.appendItem(item)
Next
End If
I have an Access Database linked with a VB project through a data source. In the database on one of the tables, I have an OLE Object field. I have saved pictures in .BMP format and .JPG format in this field. The problem I am encountering is loading this image into my application. This is what I would like to be able to do:
ButtonMeal1.BackgroundImage = IPOSDBDataSet.Meals.Rows(0).Item(5)
Where Item(5) is the column of the row where the image is stored.
Is there another way of doing this. Do I have to load the picture into the program by storing it as a variable, and then using that to change the background image of the button. There are no clear answers on the internet regarding my issue. Please help!
EDIT 1:
After doing some more research, I found some code and adjusted it to try fix my problem.
Dim ImageByteArray As Byte() = CType(IPOSDBDataSet.Meals.Rows(0).Item(5), Byte())
Dim ImageMemoryStream As MemoryStream = New IO.MemoryStream(ImageByteArray)
Dim MyImage As Image = Drawing.Image.FromStream(ImageMemoryStream)
PictureBox1.Image = MyImage
However, I receive the error "Parameter is Not Valid" with the 3rd line of the code. Would anyone be able to tell me how I could adjust my code to fix this issue, or tell me if I am doing something completely wrong?
EDIT 2:
I keep on changing the code around, but the error is always "Parameter is not valid.". What parameter is not valid?
EDIT 3:
No matter what I change it to, the error still persists. What is this parameter that is causing all my issues?
Dim ImageByteArray As Byte() = CType(IPOSDBDataSet.Meals.Rows(0).Item(5), Byte())
Dim ImageMemoryStream As MemoryStream = New IO.MemoryStream(ImageByteArray)
Dim ImageStream As Stream = ImageMemoryStream
Dim MyImage As Image = Drawing.Image.FromStream(ImageStream)
PictureBox1.Image = MyImage
EDIT 4:
Can anyone please help? I really need to be able to implement this into my program. Is there any other possible way of storing images in an access database, and importing them into my vb.net program?
Credit goes to TnTinMan from CodeProject for the answer. Hopefully this helps someone else:
Dim ImageByteArray As Byte() = CType(DataSet.Table.Rows(RowNo).Item(ItemNo), Byte())
Dim ImageMemoryStream As MemoryStream = New IO.MemoryStream(GetImageBytesFromOLEField(ImageByteArray))
Dim MyImage As Image = Drawing.Image.FromStream(ImageMemoryStream)
Friend Shared Function GetImageBytesFromOLEField(ByVal oleFieldBytes() As Byte) As Byte()
Dim BITMAP_ID_BLOCK As String = "BM"
Dim JPG_ID_BLOCK As String = ChrW(&HFF).ToString() & ChrW(&HD8).ToString() & ChrW(&HFF).ToString()
Dim PNG_ID_BLOCK As String = ChrW(&H89).ToString() & "PNG" & vbCrLf & ChrW(&H1A).ToString() & vbLf
Dim GIF_ID_BLOCK As String = "GIF8"
Dim TIFF_ID_BLOCK As String = "II*" & ChrW(&H0).ToString()
Dim imageBytes() As Byte
' Get a UTF7 Encoded string version
Dim u7 As System.Text.Encoding = System.Text.Encoding.UTF7
Dim strTemp As String = u7.GetString(oleFieldBytes)
Dim st2 As String = System.Text.Encoding.UTF8.GetString(oleFieldBytes)
' Get the first 300 characters from the string
Dim strVTemp As String = strTemp.Substring(0, 300)
' Search for the block
Dim iPos As Integer = -1
If strVTemp.IndexOf(BITMAP_ID_BLOCK) <> -1 Then
iPos = strVTemp.IndexOf(BITMAP_ID_BLOCK)
ElseIf strVTemp.IndexOf(JPG_ID_BLOCK) <> -1 Then
iPos = strVTemp.IndexOf(JPG_ID_BLOCK)
ElseIf strVTemp.IndexOf(PNG_ID_BLOCK) <> -1 Then
iPos = strVTemp.IndexOf(PNG_ID_BLOCK)
ElseIf strVTemp.IndexOf(GIF_ID_BLOCK) <> -1 Then
iPos = strVTemp.IndexOf(GIF_ID_BLOCK)
ElseIf strVTemp.IndexOf(TIFF_ID_BLOCK) <> -1 Then
iPos = strVTemp.IndexOf(TIFF_ID_BLOCK)
Else
Throw New Exception("Unable to determine header size for the OLE Object")
End If
' From the position above get the new image
If iPos = -1 Then
Throw New Exception("Unable to determine header size for the OLE Object")
End If
imageBytes = New Byte(CInt(oleFieldBytes.LongLength - iPos - 1)) {}
Array.ConstrainedCopy(oleFieldBytes, iPos, imageBytes, 0, oleFieldBytes.Length - iPos)
Return imageBytes
End Function
There isn't really such a thing as an 'image' stored in an Access table, only a binary stream. Therefore, the left hand side of your expression doesn't know that the right hand side is providing an image. You would have to stream the binary stream into a stream in VB.NET, then use System.Graphics methods to make it into a BMP or PNG or whatever. You could assign that object to the button.
still show error: index and length must refer to a location within the string.Parameter name: len
I have a problem when I download a file from a URL (This it's not my main problem), the problem comes after that.
The file that I saved from the URL can be a image, doc, PDF or ZIP.
Exists some method to know the file type when the path doesn't has the extension?
Or identify the file type from an stream?
I'm working with Visual Studio 2010 Express Edition - Framework.Net 3.5 - A Window App
Public Function DownloadFile_FromURL(ByVal URL As String, ByVal DestinationPath As String) As Boolean
DownloadFile_FromURL = False
Try
Dim vRequest As Net.HttpWebRequest
Dim vResponse As Net.HttpWebResponse
vRequest = Net.WebRequest.Create(New Uri(URL))
vRequest.Method = "GET"
vRequest.AllowAutoRedirect = True
vRequest.UseDefaultCredentials = True
vResponse = vRequest.GetResponse
If vResponse.ContentLength <> -1 Then
Dim vLen As Long = vResponse.ContentLength
Dim vWriteStream As New IO.FileStream(DestinationPath, IO.FileMode.CreateNew)
Dim vStream As IO.Stream = vResponse.GetResponseStream()
Dim vReadBytes() As Byte = New Byte(255) {}
Dim vCount As Integer = vStream.Read(vReadBytes, 0, vReadBytes.Length)
While vCount > 0
vWriteStream.Write(vReadBytes, 0, vCount)
vCount = vStream.Read(vReadBytes, 0, vReadBytes.Length)
End While
vWriteStream.Flush() : vWriteStream.Close()
vResponse.Close() : vRequest = Nothing : GCcleaner()
Dim v = System.IO.Path.GetExtension(DestinationPath)
DownloadFile_FromURL = True
End If
Catch ex As Exception
Throw New Exception(ex.mc_GetAllExceptions)
End Try
End Function
If you are using WebRequest for the download.
Dim uri As String = "http://domain.com/resource"
Dim request As HttpWebRequest = DirectCast(WebRequest.Create(uri), HttpWebRequest)
request.Method = "GET"
Dim response As HttpWebResponse = DirectCast(request.GetResponse(), HttpWebResponse)
Dim contentType = response.ContentType
' this will have the content type/ file type
You can now have a routine to save the file using a particular extension depending on the content type. for instance a content type of "image/jpeg" can be saved as *.jpg
For an Image you can load it into an Image() object and see if it throws an OutOfMemoryException -- not an image.
PDF you can read the first few bytes of it (the PDF file type info is stored there, though not sure exactly what it is at the moment).
ZIP and DOC I'm not sure about.
If you are using WebRequests you can grab the content type of the response stream. More information about the MIME/content types here: http://msdn.microsoft.com/en-us/library/ms775147.aspx