I want to upload file using a WebApi by making an ajax call and the file will save into database. I tried the code given in the this link. Here, it is saved the received da
If you want to save the file to a BLOB field in your database, then you can use the code provided in the following post: Saving any file to in the database, just convert it to a byte array?.
The relevant code is below:
public static int databaseFilePut(MemoryStream fileToPut)
{
int varID = 0;
byte[] file = fileToPut.ToArray();
const string preparedCommand = @"
INSERT INTO [dbo].[Raporty]
([RaportPlik])
VALUES
(@File)
SELECT [RaportID] FROM [dbo].[Raporty]
WHERE [RaportID] = SCOPE_IDENTITY()
";
using (var varConnection = Locale.sqlConnectOneTime(Locale.sqlDataConnectionDetails))
using (var sqlWrite = new SqlCommand(preparedCommand, varConnection))
{
sqlWrite.Parameters.Add("@File", SqlDbType.VarBinary, file.Length).Value = file;
using (var sqlWriteQuery = sqlWrite.ExecuteReader())
while (sqlWriteQuery != null && sqlWriteQuery.Read())
varID = sqlWriteQuery["RaportID"] is int ? (int) sqlWriteQuery["RaportID"] : 0;
}
return varID;
}
You can combine the approach in the link you sent with the code for committing a MemoryStream to the database provided in an answer I linked to.
You will need a specific column in your table to save the actual file name. Basically, you will need a BLOB column for the file content and another TEXT or VARCHAR column for the file name. The link you provided shows a way to obtain the name of the file.
However, as others have pointed out, you should not save files to the database. The most common way of handling file uploads is to save them to some location on the server and commit the path to the saved file to a TEXT or VARCHAR field in the database.