2020年5月8日 星期五

把Base64 轉成 Byte Array 後儲存為圖檔

專案需要將撈出來的HTML頁面產生PDF...慢慢刻太花時間外加CSS很容易跑掉,乾脆轉圖檔儲存,但用html2canvas轉完後是base64,只好轉存成byte再save圖檔給PDF用...紀錄一下參考的base64 to byte文章
 
HTML Markup
The following HTML Markup consists of an ASP.Net FileUpload control to upload the Image File and a Button control to trigger the File upload process.
<form id="form1" runat="server">
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="btnUpload" runat="server" Text="Upload"
    onclick="btnUpload_Click" />
</form>
 
 
Convert Base64 string to Byte Array using C# and VB.Net
When the Upload button is clicked, the Image file is read into a Byte Array using the BinaryReader class object.
The Byte Array is then converted into Base64 encoded string using the Convert.ToBase64String method.
Now in order to save the Base64 encoded string as Image File, the Base64 encoded string is converted back to Byte Array using the Convert.FromBase64String function.
Finally the Byte Array is saved to Folder on Disk as File using WriteAllBytes method of the File class.
C#
protected void btnUpload_Click(object sender, EventArgs e)
{
    //***Convert Image File to Base64 Encoded string***//
 
    //Read the uploaded file using BinaryReader and convert it to Byte Array.
    BinaryReader br = new BinaryReader(FileUpload1.PostedFile.InputStream);
    byte[] bytes = br.ReadBytes((int)FileUpload1.PostedFile.InputStream.Length);
 
    //Convert the Byte Array to Base64 Encoded string.
    string base64String = Convert.ToBase64String(bytes, 0, bytes.Length);
 
    //***Save Base64 Encoded string as Image File***//
 
    //Convert Base64 Encoded string to Byte Array.
    byte[] imageBytes = Convert.FromBase64String(base64String);
       
    //Save the Byte Array as Image File.
    string filePath = Server.MapPath("~/Files/" + Path.GetFileName(FileUpload1.PostedFile.FileName));
    File.WriteAllBytes(filePath, imageBytes);
}
 
VB.Net
Protected Sub btnUpload_Click(sender As Object, e As EventArgs)
    '***Convert Image File to Base64 Encoded string***
 
    'Read the uploaded file using BinaryReader and convert it to Byte Array.
    Dim br As New BinaryReader(FileUpload1.PostedFile.InputStream)
    Dim bytes As Byte() = br.ReadBytes(CInt(FileUpload1.PostedFile.InputStream.Length))
 
    'Convert the Byte Array to Base64 Encoded string.
    Dim base64String As String = Convert.ToBase64String(bytes, 0, bytes.Length)
 
    '***Save Base64 Encoded string as Image File***
 
    'Convert Base64 Encoded string to Byte Array.
    Dim imageBytes As Byte() = Convert.FromBase64String(base64String)
 
    'Save the Byte Array as Image File.
    Dim filePath As String = Server.MapPath("~/Files/" + Path.GetFileName(FileUpload1.PostedFile.FileName))
    File.WriteAllBytes(filePath, imageBytes)
End Sub
 

2020年3月23日 星期一

.Net VB 圖片上傳後變橫的

爬了下文應該是因為exif資訊的問題,上傳前必須先判斷是否需要轉角度...找了一下總算找到相關內容參考

Public Function TestRotate(sImageFilePath As String) As Boolean
    Dim rft As RotateFlipType = RotateFlipType.RotateNoneFlipNone
    Dim img As Bitmap = Image.FromFile(sImageFilePath)
    Dim properties As PropertyItem() = img.PropertyItems
    Dim bReturn As Boolean = False
    For Each p As PropertyItem In properties
      If p.Id = 274 Then
        Dim orientation As Short = BitConverter.ToInt16(p.Value, 0)
        Select Case orientation
          Case 1
            rft = RotateFlipType.RotateNoneFlipNone
          Case 3
            rft = RotateFlipType.Rotate180FlipNone
          Case 6
           rft = RotateFlipType.Rotate90FlipNone
          Case 8
           rft = RotateFlipType.Rotate270FlipNone
        End Select
      End If
    Next
    If rft <> RotateFlipType.RotateNoneFlipNone Then
      img.RotateFlip(rft)
      System.IO.File.Delete(sImageFilePath)
      img.Save(sImageFilePath, System.Drawing.Imaging.ImageFormat.Jpeg)
      bReturn = True
    End If
    Return bReturn

  End Function

需要import
System.Drawing
System.Drawing.Imaging

RotateFlipType還有很多種,但手機似乎只會遇到以上狀況所以就只用到1、3、6、8

感謝幫助到我的原文,那邊也有C#的寫法

原文網址點我

2020年3月5日 星期四

Null / DBNull / String.Empty的差異

找.net判斷null的東西時看到不錯的文章,但該文章已經失效只好自己紀錄一下...

以下是文章的紀錄:

Null跟DBNull及String.Empty這三者,或許很少有人認真的去想過這三者的差異在那,而什麼時候要用那一個去判斷?

從簡單的if去比對這三者是否相等,很快的就發現這三者是不相等的.

null != DBNull  /DBNull != string.Empty / null != string.Empty

那麼現在宣告了兩個變數,一個是string a="",另一個是string b=null; 那麼這兩個變數是各自符合那一種?

結果是

a != null;

a != DBNull

a = string.Empty

拿.Net 2.0才有的新判斷string.IsNullOrEmpty來看.也是為true

而b的部份則如下

b = null

b != dbnull

b != string.Empty

string.IsNullOrEmpty(b) = true

從這兩個例子看到什麼時候是Null,什麼時候是string.Empty,那麼DBNull呢?

DBNull的使用時機,當至資料庫查詢,符合的資料回傳的資料欄位沒有值,為null時,此時此欄位的值就=DBNull.

當至資料庫查詢,沒有符合的資料回傳時,此時回傳的結果就=Null.



Null是當物件未被初始化時的情況,例如 StreamReader reader;還沒有給new StreamReader();

ex :
object o=cmd.ExecuteScalar();(回傳一個欄位的值)
狀況1:當DB回傳有符合的資料,但該欄位沒有值時.o = DBNull 可是 o != null
狀況2:當DB回傳沒有符合的資料時, o = null可是o != DBNull
狀況3:不論是狀況1或狀況2的結果,Convert.ToString(o)=string.Empty;


感謝原作者的文章,雖然連結已失效還是貼下
https://www.dotblogs.com.tw/jeff-yeh/archive/2008/12/07/6286.aspx

2019年12月11日 星期三

FileUpload控制項批次上傳範例

找批次上傳的參考時的筆記,紀錄一下,要 .NET版本4.5才能用...


參考網址:
https://dotblogs.com.tw/mis2000lab/2012/04/26/net45_fileupload_allowmultiple



HTML畫面設計:
      注意!!只有一個 FileUpload控制項而已。
                      它的 AllowMultiple屬性已經啟動!



VB語法,範例如下:
    Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        '--註解:網站上的目錄路徑。所以不寫磁碟名稱(不寫 “實體”路徑)。
        '--           上傳後的存檔目錄,請依照您的環境作修改。

        Dim saveDir As String = "\[Book]FileUpload\Uploads\"
        Dim appPath As String = Request.PhysicalApplicationPath

        Dim tempfileName As String = Nothing
        Dim myLabel As New System.Text.StringBuilder

        '===========================================
        '== Ony .NET 4.5有這個新的 AllowMultiPle屬性
        '===========================================


        Dim fileName, savePath As String
        For Each postedFile As HttpPostedFile In FileUpload1.PostedFiles
            fileName = postedFile.FileName

            ' –完成檔案上傳的動作。
            savePath = appPath & saveDir & fileName
            postedFile.SaveAs(savePath)

            myLabel.Append("<hr>檔名---- " & fileName)

        Next

        Label1.Text = "上傳成功" & myLabel.ToString()
    End Sub





2019年11月24日 星期日

.net vb 排除特定符號字元

需要阻擋透過表單傳遞惡意傳遞sql或其他指令,本想用正則表達式但考慮到email跟一些使用者可能使用的符號所以還是作罷,最後用比對方式處理,紀錄一下參考資料

VB.NET code

Public Class Form3
    Private ReadOnly InvalidChars As String = "[" + System.Text.RegularExpressions.Regex.Replace(""";&^%$#", ".", "\$&") + "]"
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim s As String = "有特殊字符哦"
        If System.Text.RegularExpressions.Regex.Match(s, InvalidChars).Success Then
            MessageBox.Show("有特殊字符")
        Else
            MessageBox.Show("没有特殊字符")
        End If
    End Sub
End Class

參考網址:

2019年2月10日 星期日

.NET跟IIS的上傳限制設定

更新版本後的IIS以前的寫法沒用了,網路上找到的方法引用來memo當筆記

ASP.net File Upload Size

前言

從IIS7開始,IIS預設限制28MB左右的要求內容長度,而ASP.net預設則是限制4MB大小
如果一個網站的用戶想上傳100MB檔案,勢必IIS和ASP.net兩邊都要設定

實作

ASP.net Web.config裡寫下以下區段
<system.web>
 <httpRuntime  maxRequestLength="102400" executionTimeout="600"/>
</system.web>
maxRequestLength 檔案大小(KB),預設值4096 KB(4MB),所以102400KB為100MB
executionTimeout 上傳時間(秒),600秒為10分鐘
<system.webServer>
 <security>
  <requestFiltering>
   <requestLimits maxAllowedContentLength="104857600" />
  </requestFiltering>
 </security>
</system.webServer>
maxAllowedContentLength 檔案大小(byte),所以104857600(1024*1024*100)為100MB
上述system.webServer也可以透過IIS來設定
允許的內容長度上限預設值為30000000(約28MB),把它修改為104857600

如此一來,網站便可以上傳100MB大小的檔案了

加碼補充

如果當使用者上傳檔案超過限制大小時,想重新導向到自訂的錯誤頁面
在Global.asax.cs裡寫下...
protected void Application_BeginRequest(object sender, EventArgs e)
{
 HttpRuntimeSection section = (HttpRuntimeSection)ConfigurationManager.GetSection("system.web/httpRuntime");
 int maxFileSize = section.MaxRequestLength * 1024;
 if (Request.ContentLength > maxFileSize)
 {
  try
  {
   Response.Redirect("~/MySizeError.aspx");
  }
  catch (Exception ex)
  {
   
  }
 }
}


引用來源:高級打字員的技術雲

2018年8月1日 星期三

解決瀏覽器暫存網頁無法自動更新css檔案問題

瀏覽器暫存會讓網站的css檔案無法即時更新,雖然強制重整就能解決但如果用手機觀看除非清除資料不然只能等暫存更新時間才能更新,為了讓客戶可以即時看到修改乾脆在css檔案的路徑後方加上亂數,這樣瀏覽器就會以為是不同檔案重抓css了


.net vb
<link href="Style.css?v=<%=now()%>" rel="stylesheet" type="text/css">

懶得建立亂數乾脆用當下時間了,缺點是使用者會一直下載Cache檔案 XDDD