Upload file using web Api in c# - c#

I am trying to upload file using web api in c#. I tried in postman. It works properly. I was confuse how to do it in c# code .
I have tried following code but it gives error.
var request = (HttpWebRequest)WebRequest.Create("http://Api_projects/add_project");
var postData = "name=thisIsDemoName&img=" + Server.MapPath(FileUpload1.FileName) +"&info=ThisIsDemoInfo";
var data = Encoding.ASCII.GetBytes(postData);
request.Method = "POST";
request.ContentType = "multipart/form-data";
request.ContentLength = data.Length;
using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
var response = (HttpWebResponse)request.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
Response.Write(responseString);
When run the code it write following error message on screen
A PHP Error was encountered
Severity: Notice
Message: Undefined index: img
Filename: controllers/Api_projects.php
Line Number: 27
Backtrace:
File: /home/fpipj1blp4wo/public_html/ecosense.in/application/controllers/Api_projects.php
Line: 27
Function: _error_handler
File: /home/fpipj1blp4wo/public_html/ecosense.in/application/libraries/REST_Controller.php
Line: 785
Function: call_user_func_array
File: /home/fpipj1blp4wo/public_html/ecosense.in/index.php
Line: 315
Function: require_once
plz help

Sending multipart/form-data is a bit more complicated. Have a look at: Upload files with HTTPWebrequest (multipart/form-data)

Since you didn't write what are you using (.NET Framework or .NET Core,...) I will assume that you mean .NET Core Web Api.
So, I do this by creating folder (for instance Resources (this dir is in the same dir that is controllers, migrations, models,....), and inside Resource folders I create another folder called Images.
Then in desired controller, I do this:
[HttpPost]
public IActionResult Upload() {
try {
var file = Request.Form.Files[0];
var folderName = Path.Combine("Resources", "Images");
var pathToSave = Path.Combine(Directory.GetCurrentDirectory(), folderName);
if (file.Length > 0) {
var fname = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
var fullPath = Path.Combine(pathToSave, fname);
var dbPath = Path.Combine(folderName, fileName);
using (var stream = new FileStream(fullPath, FileMode.Create)) {
file.CopyTo(dbPath);
}
return Ok(new { dbPath });
}
else {
return BadRequest();
}
}
catch (Exception ex) {
return StatusCode(500, "Internal server error");
}
}
This should work. However, this uploaded files/images, are stored in Resource folder, and we need to make this folder servable. So you need to modify the Configure method in Startup.cs class
app.UseStaticFiles();
app.UseStaticFiles(new StaticFileOptions() {
FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), #"Resources")),
RequestPath = new PathString("/Resources")
});
This is just an example. There are many more ways to upload an image.
Hope it helps

Related

Unable to File Upload From Angular 8 to Asp.net Core 2.2

I have asp.net core server (using .net core 2.2) that has FileUploadController which listens to post request for incoming file.
[HttpPost("Upload")]
// public async Task<IActionResult> Upload([FromForm(Name="file")]IFormFile file) {
// public async Task<IActionResult> Upload([FromForm]IFormFile file) {
public async Task<IActionResult> Upload(IFormFile file) {
Console.WriteLine("***" + file);
if(file == null) return BadRequest("NULL FILE");
if(file.Length == 0) return BadRequest("Empty File");
Console.WriteLine("***" + host.WebRootPath);
if (string.IsNullOrWhiteSpace(host.WebRootPath))
{
host.WebRootPath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot");
}
var uploadsFolderPath = Path.Combine(host.WebRootPath, "uploads");
if (!Directory.Exists(uploadsFolderPath)) Directory.CreateDirectory(uploadsFolderPath);
var fileName = "Master" + Path.GetExtension(file.FileName);
var filePath = Path.Combine(uploadsFolderPath, fileName);
using (var stream = new FileStream(filePath, FileMode.Create))
{
await file.CopyToAsync(stream);
}
return Ok("Okay");
}
I have created angular app (using angular version 8) which can choose file to upload at ClientApplication and I have created three post service that called to the api "http://localhost:5000/api/fileupload/upload".
Standard Angular HttpClient Post. when server reads, the IFormFile is null.
const formData: FormData = new FormData();
formData.append('file', file, file.name);
// return this.http.post(this.endpoint, file);
return this.http.post(this.endpoint, formData); // Problem solved
Added HttpHeaders, I try empty headers, undefined and other propose solution from stackoverflow and google.
const header = new HttpHeaders() //1
header.append('enctype', 'multipart/form-data'); //2
header.append('Content-Type', 'multipart/form-data'); //3
If I put httpheader with resources in request, server gives 415 (unsupported media type)
I try HttpRequest from '#angular/common/http' which finally give me result that i want.
const formData: FormData = new FormData();
formData.append('file', file, file.name);
const req = new HttpRequest('POST', this.endpoint, formData);
return this.http.request(req);
I want to know is it a bug or my misunderstanding? If you check online tutorial, most of the developers use "this.HttpClient.post".
From what I read, I can use httpclient.post and angular framework will auto set the proper header for user. It seems like it's not doing the job.
After thorough investigation, first error is my mistake of using file
instead of formData, second error is header "content-type" declare in
httpinterceptor which after removed, it load the file as expected.
#Injectable()
export class JwtInterceptor implements HttpInterceptor {
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
// add authorization header with jwt token if available
// if (request.url.indexOf('/upload')) {
// return next.handle(request);
// }
const token = localStorage.getItem('token');
const currentUser = JSON.parse(localStorage.getItem('user'));
if (currentUser && token) {
request = request.clone({
setHeaders: {
Authorization: `Bearer ${token}`,
// 'Content-Type': 'application/json' <---- Main Problem.
}
});
}
return next.handle(request).pipe(catchError(err => this.handleError(err)));
}
}
Server: "https://github.com/phonemyatt/TestPlaygroundServer"
Client: "https://github.com/phonemyatt/TestPlayground"
In your first example that doesn't work, you are passing file into post(...) instead of formData. It should be:
const formData: FormData = new FormData();
formData.append('file', file, file.name);
return this.http.post(this.endpoint, formData);
The code you show for the controller appears to be correct, so this should be the only change that's required. You do not need to set any custom headers on the request that is sent from Angular.
Below code work for you
uploadSecond(file: File) {
const formData: FormData = new FormData();
formData.append('file', file, file.name);
return this.http.post('https://localhost:44393/api/fileupload/UploadSecond', formData);
}
Then in your controller
[HttpPost("UploadSecond")]
[DisableRequestSizeLimit]
public async Task<IActionResult> UploadSecond([FromForm]IFormFile file)
If you are using FormData in client you can get files like this.
[HttpPost("Upload"), DisableRequestSizeLimit]
public ActionResult Upload()
{
try
{
var file = Request.Form.Files[0];
var folderName = Path.Combine("Resources","Images");
var pathToSave = Path.Combine(Directory.GetCurrentDirectory(), folderName);
if (file.Length > 0)
{
var fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
var fullPath = Path.Combine(pathToSave, fileName);
var dbPath = Path.Combine(folderName, fileName);
using (var stream = new FileStream(fullPath, FileMode.Create))
{
file.CopyTo(stream);
}
return Ok(new { dbPath });
}
else
{
return BadRequest();
}
}
catch (Exception ex)
{
return StatusCode(500, "Internal server error");
}
}

How can I post image from UWP to .NET core web api?

Now I have configured for UWP photo post to web api part which is using HttpClient.
Uri uri = new Uri("http://localhost:50040/api/Upload");
IInputStream inputStream = await photoFile.OpenAsync(FileAccessMode.Read);
HttpMultipartFormDataContent multipartContent = new HttpMultipartFormDataContent();
multipartContent.Add(new HttpStreamContent(inputStream), "myFile", photoFile.Name);
Windows.Web.Http.HttpClient newclient = new Windows.Web.Http.HttpClient();
Windows.Web.Http.HttpResponseMessage response = await client.PostAsync(uri, multipartContent);
But I don't know how to set for the server side which is my .NET core web api to get the image which post from my UWP application.Please Help me, thank you.
But I don't know how to set for the server side which is my .NET core web api
Please reference the File uploads official tutorial to create your server side. For example, add POST method as following sample code showed to receive the UWP client sent file with the client code you showed above.
// POST api/values
[HttpPost]
public async Task<IActionResult> Post(IFormFile myFile)
{
// full path to file in temp location, you could change this
var filePath = Path.GetTempFileName();
if (myFile.Length > 0)
{
using (var stream = new FileStream(filePath, FileMode.Create))
{
await myFile.CopyToAsync(stream);
}
}
// process uploaded files
// Don't rely on or trust the FileName property without validation.
return Ok(new { filePath, myFile.Length });
}
More details you could also reference the official sample.
In Web API Controller
public IHostingEnvironment _environment;
public UploadFilesController(IHostingEnvironment environment) // Create Constructor
{
_environment = environment;
}
[HttpPost("UploadImages")]
public Task<ActionResult<string>> UploadImages([FromForm]List<IFormFile> allfiles)
{
string filepath = "";
foreach (var file in allfiles)
{
string extension = Path.GetExtension(file.FileName);
var upload = Path.Combine(_environment.ContentRootPath, "ImageFolderName");
if (!Directory.Exists(upload))
{
Directory.CreateDirectory(upload);
}
string FileName = Guid.NewGuid() + extension;
if (file.Length > 0)
{
using (var fileStream = new FileStream(Path.Combine(upload, FileName), FileMode.Create))
{
file.CopyTo(fileStream);
}
}
filepath = Path.Combine("ImageFolderName", FileName);
}
return Task.FromResult<ActionResult<string>>(filepath);
}
In yourpage.xaml.cs
using Windows.Storage;
using Windows.Storage.Pickers;
.....
StorageFile file;
......
private async void btnFileUpload_Click(object sender, RoutedEventArgs e) // Like Browse button
{
try
{
FileOpenPicker openPicker = new FileOpenPicker();
openPicker.ViewMode = PickerViewMode.Thumbnail;
openPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
openPicker.FileTypeFilter.Add(".jpg");
openPicker.FileTypeFilter.Add(".png");
file = await openPicker.PickSingleFileAsync();
if (file != null)
{
//fetch file details
}
}
catch (Exception ex)
{
}
}
//When upload file
var http = new HttpClient();
var formContent = new HttpMultipartFormDataContent();
var fileContent = new HttpStreamContent(await file.OpenReadAsync());
formContent.Add(fileContent, "allfiles", file.Name);
var response = await http.PostAsync(new Uri("Give API Path" + "UploadImages", formContent);
string filepath = Convert.ToString(response.Content); //Give path in which file is uploaded
Hope this code helps you...
But remember formContent.Add(fileContent, "allfiles", file.Name); line is important and allfiles is that name of parameter to fetch files in web api method "public Task<ActionResult<string>> UploadImages([FromForm]List<IFormFile> **allfiles**)"
Thanks!!!

HttpGet return error 405

Using ASP Web API, I create a method that takes an ID then deliver a pdf file, then using Google docs viewer, or similar service, to view the file,
The code looks something like this,
[HttpGet]
public HttpResponseMessage GetAttachment(string id)
{
try {
string mapping = #"\\192.168.3.3\Archieve";
string sourcedir = #"\Digital\";
string filename = id + ".pdf";
string sourceFullPath = mapping + sourcedir + filename;
byte[] dataBytes = new byte[0];
// connect to other network using custom credential
var credential = new NetworkCredential("user", "pass", "192.168.3.3");
using (new NetworkConnection(mapping, credential)) {
dataBytes = File.ReadAllBytes(sourceFullPath);
}
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK);
response.Content = new StreamContent(new MemoryStream(dataBytes));
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
response.Content.Headers.ContentDisposition.FileName = filename;
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
return response;
}
catch (Exception ex) {
return Request.CreateResponse(HttpStatusCode.Gone, ex.Message);
}
}
With this code, I'm able to download the pdf file when I open the link on web browser, but when I try to display it using Google docs viewer, like this
https://docs.google.com/viewerng/viewer?url=http://myserver/webapi/api/File/GetAttachment/0317101532
Google failed to display the file without error,
And when I use other service like https://www.pdfescape.com/open/ the error is The remote server returned an error: (405) Method Not Allowed.
EDIT: I think both Google Docs viewer and pdfescape need direct link to the file, can I generate direct link on Web API controller?
Try to copy the file to local, and then return the file link, something like this
[HttpGet]
public IHttpActionResult GetAttachment(string id)
{
try {
string mapping = #"\\192.168.3.3\Archieve";
string sourcedir = #"\Digital\";
string filename = id + ".pdf";
string sourceFullPath = mapping + sourcedir + filename;
byte[] dataBytes = new byte[0];
// connect to other network using custom credential
var credential = new NetworkCredential("user", "pass", "192.168.3.3");
using (new NetworkConnection(mapping, credential)) {
dataBytes = File.ReadAllBytes(sourceFullPath);
}
// write file to local
string destFullPath = string.Format("{0}/Content/Data//{2}", HttpContext.Current.Server.MapPath("~"), filename);
File.WriteAllBytes(destFullPath, dataBytes);
// return the file name,
return Ok(filename);
// then you can view your docs using Google Viewer like this
// https://docs.google.com/viewer?url=http://[YOUR_SERVER_BASE_URL]/content/data/[FILENAME]
}
catch (Exception ex) {
return Content(HttpStatusCode.PreconditionFailed, ex.Message);
}
}
Don't forget to add required permission on 'Content' folder

How can I simultaneously pass args and upload a file to a Web API Controller Method?

I decided that my question here isn't really what I want to do - the XML I need to send is a lot longer, potentially, than I really want to send in a URI.
It didn't "feel" right doing that, and this unsealed the deal.
I need to send both a couple of args AND a file to my Web API app from a client (handheld/CF) app.
I may have found the code for receiving that, from here [
http://www.asp.net/web-api/overview/working-with-http/sending-html-form-data,-part-2]
Specifically, Wasson's Controller code here looks like it very well might work:
public async Task<HttpResponseMessage> PostFile()
{
// Check if the request contains multipart/form-data.
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
string root = HttpContext.Current.Server.MapPath("~/App_Data");
var provider = new MultipartFormDataStreamProvider(root);
try
{
StringBuilder sb = new StringBuilder(); // Holds the response body
// Read the form data and return an async task.
await Request.Content.ReadAsMultipartAsync(provider);
// This illustrates how to get the form data.
foreach (var key in provider.FormData.AllKeys)
{
foreach (var val in provider.FormData.GetValues(key))
{
sb.Append(string.Format("{0}: {1}\n", key, val));
}
}
// This illustrates how to get the file names for uploaded files.
foreach (var file in provider.FileData)
{
FileInfo fileInfo = new FileInfo(file.LocalFileName);
sb.Append(string.Format("Uploaded file: {0} ({1} bytes)\n", fileInfo.Name, fileInfo.Length));
}
return new HttpResponseMessage()
{
Content = new StringContent(sb.ToString())
};
}
catch (System.Exception e)
{
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
}
}
...but now I need to know how to send it; other calls from the client are of the form:
http://<IPAddress>:<portNum>/api/<ControllerName>?arg1=Bla&arg2=Blee
but how does the file I need to send/attach get passed along? It is a XML file, but I don't want to append the whole thing to the URI, as it can be quite large, and doing so would be horrendously weird.
Does anybody know how to accomplish this?
UPDATE
Following the crumbs tvanfosson dropped below, I found code here which I think I can adapt to work on the client:
var message = new HttpRequestMessage();
var content = new MultipartFormDataContent();
foreach (var file in files)
{
var filestream = new FileStream(file, FileMode.Open);
var fileName = System.IO.Path.GetFileName(file);
content.Add(new StreamContent(filestream), "file", fileName);
}
message.Method = HttpMethod.Post;
message.Content = content;
message.RequestUri = new Uri("http://localhost:3128/api/uploading/");
var client = new HttpClient();
client.SendAsync(message).ContinueWith(task =>
{
if (task.Result.IsSuccessStatusCode)
{
//do something with response
}
});
...but that depends on whether the Compact Framework supports MultipartFormDataContent
UPDATE 2
Which it doesn't, according to How can i determine which .Net features the compact framework has?
UPDATE 3
Using the Bing Search Code for C# extension, I mashed "h", chose "How do I", entered "send file via http" and got this:
WebRequest request = WebRequest.Create("http://www.contoso.com/PostAccepter.aspx ");
request.Method = "POST";
string postData = "This is a test that posts this string to a Web server.";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteArray.Length;
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
WebResponse response = request.GetResponse();
Console.WriteLine(((HttpWebResponse)response).StatusDescription);
dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
Console.WriteLine(responseFromServer);
reader.Close();
dataStream.Close();
response.Close();
As I need to add a couple of string args in addition to the file (which I assume I can add via the postData byte array), can I do that by adding more calls to dataStream.Write()? IOW, is this sensible (first and third lines differ):
WebRequest request = WebRequest.Create("http://MachineName:NNNN/api/Bla?str1=Blee&str2=Bloo");
request.Method = "POST";
string postData = //open the HTML file and assign its contents to this, or make it File postData instead of string postData?
// the rest is the same
?
UPDATE 4
Progress: This, such as it is, is working:
Server code:
public string PostArgsAndFile([FromBody] string value, string serialNum, string siteNum)
{
string s = string.Format("{0}-{1}-{2}", value, serialNum, siteNum);
return s;
}
Client code (from Darin Dimitrov in this post):
private void ProcessRESTPostFileData(string uri)
{
using (var client = new WebClient())
{
client.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
var data = "=Short test...";
var result = client.UploadString(uri, "POST", data);
//try this: var result = client.UploadFile(uri, "bla.txt");
//var result = client.UploadData()
MessageBox.Show(result);
}
}
Now I need to get it sending a file instead of a string in the [FromBody] arg.
You should look into using multipart/form-data with a custom media type formatter that will extract both the string properties and the uploaded XML file.
http://lonetechie.com/2012/09/23/web-api-generic-mediatypeformatter-for-file-upload/

Uploading an image using C# and WebRequest?

Here is the working code in Python (using cURL):
#!/usr/bin/python
import pycurl
c = pycurl.Curl()
values = [
("key", "YOUR_API_KEY"),
("image", (c.FORM_FILE, "file.png"))]
# OR: ("image", "http://example.com/example.jpg"))]
# OR: ("image", "BASE64_ENCODED_STRING"))]
c.setopt(c.URL, "http://imgur.com/api/upload.xml")
c.setopt(c.HTTPPOST, values)
c.perform()
c.close()
Here's what I have in C#:
public void UploadImage()
{
//I think this line is doing something wrong.
//byte[] x = File.ReadAllBytes(#"C:\Users\Sergio\documents\visual studio 2010\Projects\WpfApplication1\WpfApplication1\Test\hotness2.jpg");
//If I do it like this, using a direct URL everything works fine.
string parameters = #"key=1b9189df79bf3f8dff2125c22834210903&image=http://static.reddit.com/reddit.com.header.png"; //Convert.ToBase64String(x);
WebRequest webRequest = WebRequest.Create(new Uri("http://imgur.com/api/upload"));
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.Method = "POST";
byte[] bytes = Encoding.ASCII.GetBytes(parameters);
Stream os = null;
try
{ // send the Post
webRequest.ContentLength = bytes.Length; //Count bytes to send
os = webRequest.GetRequestStream();
os.Write(bytes, 0, bytes.Length); //Send it
}
catch (WebException ex)
{
MessageBox.Show(ex.Message, "HttpPost: Request error");
}
finally
{
if (os != null)
{
os.Close();
}
}
try
{ // get the response
WebResponse webResponse = webRequest.GetResponse();
StreamReader sr = new StreamReader(webResponse.GetResponseStream());
MessageBox.Show(sr.ReadToEnd().Trim());
}
catch (WebException ex)
{
MessageBox.Show(ex.Message, "HttpPost: Response error");
}
}
Now, the things I noticed is that when I changed my API key in the parameters string to "239231" or whatever number, the response I got was: "Invalid API key." So I think something must be working right.
I placed my correct API key and now I get a different response: "Invalid image format. Try uploading a JPEG image."
The service I'm using accepts almost every image format, so I am 100% certain the error is in the way I'm sending the file. Can anyone shed some light?
EDIT!!!
It turns out when I upload a JPG image I get that gray box thing. If I upload a big jpg image I don't get anything. For example: http://i.imgur.com/gFsUY.jpg
When I upload PNG's, the image uploaded doesn't even show.
I'm certain the issue is the encoding. What can I do?
EDIT 2!!!
Now I'm 100% certain that the problem lies in the first line of the method. The File.ReadAllBytes() must be doing something wrong. If I upload a URL file, every works peachy: http://imgur.com/sVH61.png
I wonder what encoding I should use. :S
Try this:
string file = #"C:\Users\Sergio\documents\visual studio 2010\Projects\WpfApplication1\WpfApplication1\Test\Avatar.png";
string parameters = #"key=1df918979bf3f8dff2125c22834210903&image=" +
Convert.ToBase64String(File.ReadAllBytes(file));
You should correctly form a multipart POST request. See an example here: Upload files with HTTPWebrequest (multipart/form-data)
Read image posted by in API
public IHttpActionResult UpdatePhysicianImage(HttpRequestMessage request)
{
try
{
var form = HttpContext.Current.Request.Form;
var model = JsonConvert.DeserializeObject<UserPic>(form["json"].ToString());
bool istoken = _appdevice.GettokenID(model.DeviceId);
if (!istoken)
{
statuscode = 0;
message = ErrorMessage.TockenNotvalid;
goto invalidtoken;
}
HttpResponseMessage result = null;
var httpRequest = HttpContext.Current.Request;
if (httpRequest.Files.Count > 0)
{
var docfiles = new List<string>();
foreach (string file in httpRequest.Files)
{
var postedFile = httpRequest.Files[file];
// var filePath = uploadPath + postedFile.FileName;
// string fileUrl = Utility.AbsolutePath("~/Data/User/" + model.UserId.ToString());
string fileUrl = Utility.AbsolutePath("~/" + Utility.UserDataFolder(model.UserId, "Document"));
if (!Directory.Exists(fileUrl))
{
Directory.CreateDirectory(fileUrl);
Directory.CreateDirectory(fileUrl + "\\" + "Document");
Directory.CreateDirectory(fileUrl + "\\" + "License");
Directory.CreateDirectory(fileUrl + "\\" + "Profile");
}
string imageUrl = postedFile.FileName;
string naviPath = Utility.ProfileImagePath(model.UserId, imageUrl);
var path = Utility.AbsolutePath("~/" + naviPath);
postedFile.SaveAs(path);
docfiles.Add(path);
if (model.RoleId == 2)
{
var doctorEntity = _doctorProfile.GetNameVideoChat(model.UserId);
doctorEntity.ProfileImagePath = naviPath;
_doctorProfile.UpdateDoctorUpdProfile(doctorEntity);
}
else
{
var patientEntity = _PatientProfile.GetPatientByUserProfileId(model.UserId);
patientEntity.TumbImagePath = naviPath;
_PatientProfile.UpdatePatient(patientEntity);
}
}
result = Request.CreateResponse(HttpStatusCode.Created, docfiles);
}
else
{
result = Request.CreateResponse(HttpStatusCode.BadRequest);
}
}
catch (Exception e)
{
statuscode = 0;
message = "Error" + e.Message;
}
invalidtoken:
return Json(modeldata.GetData(statuscode, message));
}
Try changing :-
"application/x-www-form-urlencoded"
to
"multipart/form-data"
Try adding the content-type for the jpg into your multipart boundary.
See this uRL for examples (at the end)
http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4.2
Shot in the dark, but maybe create an instance of Image, save the file to a Stream and use that to read the bytes into an array then upload it.
As in:
Image i = System.Drawing.Image.FromFile("wut.jpg");
Stream stm = new Stream();
System.Drawing.Imaging.Encoder myEncoder = System.Drawing.Imaging.Encoder.Quality;
System.Drawing.Imaging.EncoderParameters paramz = new System.Drawing.Imaging.EncoderParameters(1);
myEncoderParameter = new EncoderParameter(myEncoder, 100L);
paramz.Param[0] = myEncoderParameter;
i.Save(stm, System.Drawing.Imaging.ImageFormat.Jpeg, paramz);
/* I'm lazy: code for reading Stream into byte[] here */

Categories

Resources