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
Emre Dereli
NA
9
698
Post Image to Asp.Net Web API from OpenFileDialog
Aug 16 2018 3:40 AM
I want to post image I select from OpenFileDialog to Web API. Then i will read url.
Like :
>"https://localhost:1111/api/images/1.jpg"
Image:
BitmapImage src =
new
BitmapImage();
src.BeginInit();
src.CacheOption = BitmapCacheOption.OnLoad;
src.UriSource =
new
Uri(path);
src.EndInit();
productImage.Source = src;
Button_Click :
private
void
Button_Click(
object
sender, RoutedEventArgs e)
{
OpenFileDialog fileDialog =
new
OpenFileDialog();
fileDialog.Multiselect =
false
;
fileDialog.Filter =
"Image files (*.jpg, *.jpeg, *.jpe, *.jfif, *.png) | *.jpg; *.jpeg; *.jpe; *.jfif; *.png"
;
if
(fileDialog.ShowDialog() ==
true
){SendImage(
new
ImageDTO() { image =fileDialog.FileName });}}
SendImage():
public
bool
SendImage(ImageDTO dto)
{
string
url =
"http://localhost:52185/api/StoreImage"
;
var wc =
new
WebClient();
wc.Headers.Add(
"Content-Type"
,
"application/x-www-form-urlencoded"
);
var parameters =
new
NameValueCollection(){{
"image"
, dto.image }};
var res = wc.UploadValues(url,
"POST"
,parameters);
return
true
;}
This line throws :
var res = wc.UploadValues(url,
"POST"
,parameters);
> System.Net.WebException: 'The remote server returned an error: (500)
> Internal Server Error.'
ImageDTO :
public
class
ImageDTO
{
public
string
image;
}
ImagesController.cs :
public
class
ImagesController :ApiController
{
[HttpPost[Route(
"api/StoreImage"
)]
public
string
StoreImage(ImageDTO request){
var buffer = Convert.FromBase64String(request.image);
HttpPostedFileBase objFile = (HttpPostedFileBase)
new
MemoryPostedFile(buffer);
//Do whatever you want with filename and its binaray data.
try
{
if
(objFile !=
null
&& objFile.ContentLength > 0)
{
string
path =
""
;objFile.SaveAs(path);
//Don't Forget to save path to DB
}
}
catch
(Exception ex)
{
}
return
"OK"
;}}
It is a WPF application. I have never used Asp.Net Web API. How can i do this?
Reply
Answers (
1
)
Updating data model with database
Can we store some data into session in entity framewrok