TECHNOLOGIES
FORUMS
JOBS
BOOKS
EVENTS
INTERVIEWS
Live
MORE
LEARN
Training
CAREER
MEMBERS
VIDEOS
NEWS
BLOGS
Sign Up
Login
No unread comment.
View All Comments
No unread message.
View All Messages
No unread notification.
View All Notifications
Answers
Post
An Article
A Blog
A News
A Video
An EBook
An Interview Question
Ask Question
Forums
Monthly Leaders
Forum guidelines
First Last
NA
648
72.4k
Using Angular 8 and Asp.Net Web Api to upload an image file
Nov 11 2019 1:56 PM
I want to use Angular 8 with an Asp.Net Web Api to upload an image file and store it into a SQL server database table where the image column is defined as
varbinary
.
Note: I can do this using an ASP.Net web form just fine (I included it below). So I am trying to mimic that web form upload but using Angular as the front-end.
For uploading a file in Angular 8, I used this advice:
https://www.tutsmake.com/new-angular-8-upload-file-or-image-tutorial-example/
My issue is, how do I get the Angular uploaded image file into a varbinary format to pass along to Asp.Net Web Api? Is the image file binary data? If not, can it be converted to binary in Angular?
I am using Angular 8, Asp.Net Web Api with ADO.Net and a stored procedure to insert the image into the table.
Note: not all the code is included for simplicity.
My SQL server table definition - where by the image is defined as varbinary:
CREATE TABLE [dbo].[tblImages]
(
[ImageId] [int] IDENTITY(1,1) NOT NULL,
[ImageData] [varbinary](max) NOT NULL
CONSTRAINT [PK_Image] PRIMARY KEY CLUSTERED
(
[ImageId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF,
ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
My SQL server insert stored procedure:
CREATE procedure [dbo].[InsertImages]
@ImageData varbinary(max)
AS
BEGIN
SET NOCOUNT ON;
INSERT INTO dbo.tblImages (
ImageData )
VALUES (
@ImageData )
RETURN 0
END
The Angular component method code:
// This is from: https://www.tutsmake.com/new-angular-8-upload-file-or-image-tutorial-example/
// but modified to use my Asp.Net web api.
fileData: File = null;
// Is the image file binary data? If not, can it be converted here to binary?
fileProgress(fileInput: any) {
this.fileData = <File>fileInput.target.files[0];
}
onSubmit() {
const formData = new FormData();
formData.append('file', this.fileData);
// Call the service to add the image.
this.imageService.addImage(formData).subscribe(
() => {
this.message = 'Image Loaded Successfully';
}
}
My Angular Image service method:
// The Asp.Net Web Api endpoint.
url = "http://localhost:50454/Api/Image";
addImage(image: Image): Observable<Image> {
const httpOptions = {
headers: new HttpHeaders({ "Content-Type": "application/json" })
};
return this.http.post<Image>(this.url + "/AddImage/", image, httpOptions);
}
My Angular Model class:
export class Image {
ImageId: string;
ImageData: string; <--- Is string correct as there is no binary type?
}
My Asp.Net Web Api data model:
namespace PrototypeWebApi2.Models
{
public class Image
{
public int ImageId { get; set; }
public string ImageData { get; set; } <--- Is string correct as there is no binary type?
}
}
My Asp.Net Web Api method:
[HttpPost]
[Route("AddImage")]
public IHttpActionResult PostImage(Image data)
{
try
{
return Ok(dataaccesslayer.AddImage(data));
}
catch (Exception)
{
throw;
}
}
My Asp.Net Web Api data access layer method:
public int AddImage(Image image)
{
try
{
using (SqlConnection con = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand("InsertImages", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("@ImageData", image.ImageData);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
return 1;
}
catch
{
throw;
}
}
---------------
My Asp.Net Web form code that uploads an image file and works fine:
HTML:
<%@ Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="AdminPage.aspx.cs" Inherits="Media.Admin.AdminPage" %>
<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
<h1>Administration</h1>
<hr />
<h3>Add Image:</h3>
<table>
<tr>
<td><asp:Label ID="LabelAddImageFile" runat="server">Image File:</asp:Label></td>
<td>
<asp:FileUpload ID="MediaUploadFile" runat="server" />
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" Text="* Image file path required." ControlToValidate="MediaUploadFile" SetFocusOnError="true" Display="Dynamic"></asp:RequiredFieldValidator>
</td>
</tr>
</table>
<p></p>
<asp:Button ID="AddMediaButton" runat="server" Text="Add Media" OnClick="AddMediaButton_Click" CausesValidation="true" CssClass="btn btn-primary"/>
<asp:Label ID="LabelAddStatus" runat="server" Text=""></asp:Label>
<p></p>
</asp:Content>
Code behind:
protected void AddMediaButton_Click(object sender, EventArgs e)
{
string strErrorMessage = "";
string fileExtension = "";
int fileSize = 0;
Boolean fileOK = false;
// Get the image file that was selected. References the ASP.Net control.
HttpPostedFile postedFile = MediaUploadFile.PostedFile;
fileExtension = Path.GetExtension(fileName).ToLower();
if (MediaUploadFile.HasFile)
{
String[] allowedExtensions = { ".gif", ".png", ".jpeg", ".jpg", ".bmp" };
for (int i = 0; i < allowedExtensions.Length; i++)
{
if (fileExtension == allowedExtensions[i])
{
fileOK = true;
}
}
}
else
{
LabelAddStatus.Visible = true;
LabelAddStatus.ForeColor = System.Drawing.Color.Red;
LabelAddStatus.Text = "No image file was selected for upload.";
}
if (fileOK)
{
Stream stream = postedFile.InputStream;
BinaryReader binaryReader = new BinaryReader(stream);
// Read the file into a array of bytes.
Byte[] bytes = binaryReader.ReadBytes((int)stream.Length);
try
{
dbFunc.OpenDB();
SqlCommand cmd = new SqlCommand("dbo.InsertImages", dbFunc.objConn);
cmd.Parameters.Clear();
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@ImageData", SqlDbType.VarBinary).Value = bytes;
cmd.ExecuteNonQuery();
string pageUrl = Request.Url.AbsoluteUri.Substring(0, Request.Url.AbsoluteUri.Count()- Request.Url.Query.Count());
Response.Redirect(pageUrl + "?MediaAction=add");
}
catch (Exception ex)
{
strErrorMessage = "Insert error in AddMediaButton_Click(), on call to InsertImages procedure. Error: " + ex.Message + " Source: " + ex.Source;
// Set the UI.
LabelAddStatus.Visible = true;
LabelAddStatus.ForeColor = System.Drawing.Color.Red;
LabelAddStatus.Text = "Unable to insert the new image file to the database. " + strErrorMessage;
}
finally
{
dbFunc.CloseDB();
}
}
else
{
LabelAddStatus.Visible = true;
LabelAddStatus.ForeColor = System.Drawing.Color.Red;
LabelAddStatus.Text = "Unable to accept the file type. Only these (.gif, .png, .jpeg, .jpg, .bmp, .mpeg, .mpg and .mp4) can be uploaded";
}
}
Reply
Answers (
2
)
Jquery Data table integration in angular project.
Angular beginner tutorial