仅使用一种方法将多个图像转换为二进制

时间:2017-07-07 08:59:17

标签: c# asp.net file-upload

对于我的Little应用程序,我编写了一个方法将图像转换为二进制文件,然后将其保存在数据库中。我现在要做的是找到使同一方法可以被其他fileUpload重用的方法。这意味着,如果我有两个fileUploads,例如。

                            图片1                                            
        <div class="col-md-3">
            <div class="form-group">
                <label for="image2">Image 2</label>
                <asp:FileUpload ID="Upload2" runat="server" ForeColor="Blue" />
            </div>
        </div>

我应该能够修改下面的方法来处理图像,而不必再次重写方法

 private byte[]ConvertImage()
        {

            byte[] bytes = null;
           // byte[] bytes2 = null;
            try
            {

                HttpPostedFile postedFile = Upload1.PostedFile;


                string filename = Path.GetFileName(postedFile.FileName);
                string fileExtension = Path.GetExtension(filename);
                int filesize = postedFile.ContentLength;

                Stream stream = postedFile.InputStream;
                BinaryReader binaryreader = new BinaryReader(stream);

                bytes = binaryreader.ReadBytes((int)stream.Length);
                return bytes;
            }
            catch (Exception ex)
            {
                return null;
            }


        }

以上代码是我只使用一个fileUpload但我想使用它而不必重写整个代码

2 个答案:

答案 0 :(得分:0)

将公共代码提取到函数中:

private void ConvertImages() {
  try {
    //Process first file.
    HttpPostedFile postedFile = Upload1.PostedFile;
    byte[] ReadImage(postedFile);
    //Now do whatever you want with first file. Maybe save it?

    //Process second file.
    postedFile = Upload2.PostedFile;
    byte[] ReadImage(postedFile);
    //Now do whatever you want with second file. Maybe save it?

  } catch (Exception ex) {
    //Handle exceptions.
  }
}

private byte[] ReadImage(HttpPostedFile postedFile) {
    string filename = Path.GetFileName(postedFile.FileName);
    string fileExtension = Path.GetExtension(filename);
    int filesize = postedFile.ContentLength;

    Stream stream = postedFile.InputStream;
    BinaryReader binaryreader = new BinaryReader(stream);

    return binaryreader.ReadBytes((int) stream.Length);
}

答案 1 :(得分:0)

private byte [] ConvertImage(FileUpload file)         {

        byte[] bytes = null;
       // byte[] bytes2 = null;
        try
        {

            HttpPostedFile postedFile = file.PostedFile;


            string filename = Path.GetFileName(postedFile.FileName);
            string fileExtension = Path.GetExtension(filename);
            int filesize = postedFile.ContentLength;

            Stream stream = postedFile.InputStream;
            BinaryReader binaryreader = new BinaryReader(stream);

            bytes = binaryreader.ReadBytes((int)stream.Length);
            return bytes;
        }
        catch (Exception ex)
        {
            return null;
        }


    }

我必须让它发挥作用