upload file from phonegap camera to .Net web api - angularjs

Server side
public class UploadController : ApiController
{
public async Task<HttpResponseMessage> Post()
{
// Check whether the POST operation is MultiPart?
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
// Prepare CustomMultipartFormDataStreamProvider in which our multipart form
// data will be loaded.
string fileSaveLocation = HttpContext.Current.Server.MapPath("~/App_Data");
CustomMultipartFormDataStreamProvider provider = new CustomMultipartFormDataStreamProvider(fileSaveLocation);
List<string> files = new List<string>();
try
{
// Read all contents of multipart message into CustomMultipartFormDataStreamProvider.
await Request.Content.ReadAsMultipartAsync(provider);
foreach (MultipartFileData file in provider.FileData)
{
files.Add(Path.GetFileName(file.LocalFileName));
}
// Send OK Response along with saved file names to the client.
return Request.CreateResponse(HttpStatusCode.OK, files);
}
catch (System.Exception e)
{
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
}
}
}
public class CustomMultipartFormDataStreamProvider : MultipartFormDataStreamProvider
{
public CustomMultipartFormDataStreamProvider(string path) : base(path) { }
public override string GetLocalFileName(HttpContentHeaders headers)
{
return headers.ContentDisposition.FileName.Replace("\"", string.Empty);
}
}
Client side code, After I get the imageURI from camera send it to below
function send(imageURI) {
var options = new FileUploadOptions();
options.fileKey = "file";
options.fileName = imageURI.substr(imageURI.lastIndexOf('/') + 1);
options.mimeType = "image/jpeg";
options.chunkedMode = false;
options.headers = {
Connection: "close"
}
var params = {};
params.value1 = "test";
params.value2 = "param";
options.params = params;
var ft = new FileTransfer();
ft.upload(imageURI, encodeURI("http://localhost/api/api/upload"), win, fail, options);
}
function win(r) {
console.log("Code = " + r.responseCode);
console.log("Response = " + r.response);
console.log("Sent = " + r.bytesSent);
}
function fail(error) {
alert("An error has occurred: Code = " + error.code);
alert("upload error source " + error.source);
alert("upload error target " + error.target);
}
I get error code 1 on the fail function. is their anything wrong with server side code? can I send ImageURI the above web api i wrote?

the code seemed to be working fine. The server user which was set on IIS did not have the proper permissions to do the write hence it was returning error. thanks

Related

HttpClient post body param is not sent correctly when using 'application/x-www-form-urlencoded' content type request header

I am posting request using httpClient like:
I have imported HttpClientModule in app.module.js for http get and post request.
const httpOptionsWithCookie = {
headers: new HttpHeaders({ 'Content-Type': 'application/x-www-form-urlencoded'}),
withCredentials: true
};
this.baseUrl ("link of API")
postArguments is an object like " {name:"xyz",company:"abc"}"
this.http.post(this.baseUrl, postArguments, httpOptionsWithCookie);
I am using angular5 in front end and spring mvc at back end
I am new in angular5.
API side code :
**spring mvc imports
#RestController
#RequestMapping(value = "/api/leavePeriod")
public class LeavePeriodControllerApi {
private static LogHelper logHelper = LogHelper
.getInstance(LeaveApplicationControllerApi.class);
#Autowired
HttpSession session;
#Autowired
Environment env;
#Autowired
ILeavePeriodService service;
#Autowired
ISecurityCommonService securityCommonService;
#Autowired
ILeaveCategoryService leaveCategoryService;
#Autowired
ICompanyService companyService;
#Autowired
LeavePeriodValidator leavePeriodValidator;
private User user = new User();
private String LOGINUSER = "";
#RequestMapping(value = "/viewLeavePeriod", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
public Map<String, Object> viewLeavePeriod( #ModelAttribute LeavePeriodForm form,HttpServletRequest request,#RequestParam(value ="companyId" ,required = false)
String companyId, #RequestParam(value ="leaveCategoryId", required = false)
String leaveCategoryId )throws HRAlignBaseException {
user = (User) session.getAttribute("user");
LOGINUSER = "LoginUser " + user.getEmpName() + " loginuser empCode "
+ user.getEmpCode();
Map<String, Object> returnMap = new HashMap<String, Object>();
try{
if(companyId!= null && companyId!="")
{
form.setCompanyId(Integer.parseInt(companyId));
}
if(leaveCategoryId!= null && leaveCategoryId!="")
{
form.setLeaveCategoryId(Integer.parseInt(leaveCategoryId));
}
returnMap = service.view(form);
returnMap.put("periodList", form.getLeavePeriodVoList());
returnMap.put("comId", form.getCompanyId());
returnMap.put("leaveCatId", form.getLeaveCategoryId());
} catch (Exception e) {
e.printStackTrace();
}
logHelper
.info("################"
+ LOGINUSER
+ "############# END Enter LeavePeriodController viewLeavePeriod");
return returnMap;
}
}
the same http post request work in angularjs but it's not working in angular5.
Also when doing the same http post from ARC, it's working fine but not working for angular5
for 'Content-Type': 'application/x-www-form-urlencoded' form data should be sent like "menuId=5&buttonRights=adfasdfad&abc=aasdfasdfd" and not in json format so this feature available in angularjs(ngResource)but not in angular 5(HttpClient).
this is a standard way to post data.
Below code is for simple object.
import { URLSearchParams } from "#angular/http"
testRequest() {
let data = new URLSearchParams();
data.append('username', username);
data.append('password', password);
this.http
.post('/api', data)
.subscribe(data => {
alert('ok');
}, error => {
console.log(error.json());
});
}
if you want to post object or nested object ,you have to manually convert the object to query string using below code.
jsonTransformRequest (data) {
var param = function (obj) {
var query = '';
var name, value, fullSubName, subValue, innerObj, i;
for (name in obj) {
value = obj[name];
if (value instanceof Array) {
for (i = 0; i < value.length; ++i) {
subValue = value[i];
fullSubName = name + '[' + i + ']';
innerObj = {};
innerObj[fullSubName] = subValue;
query += param(innerObj) + '&';
}
} else if (value instanceof Object) {
for (let subName in value) {
subValue = value[subName];
fullSubName = name + '.' + subName;
innerObj = {};
innerObj[fullSubName] = subValue;
query += param(innerObj) + '&';
}
} else if (value !== undefined && value !== null) {
query += encodeURIComponent(name) + '=' + encodeURIComponent(value) + '&';
}
}
return query.length ? query.substr(0, query.length - 1) : query;
};
var ret = (data != null && typeof data === 'object') ? param(data) :
data;
return ret;
};

get broken excel file from Spring server

really don't now what to do.
i have on my server xls file and i wont to download it from my client.
i actually do it but the file getting in some weird langue and absolutely broken.
client : angular
server: spring 4
Code
Client
function getXCEL() {
self.onXCELProcess = true;
AdminService.getXL(MotherService.getAppMember())
.then(
function (response) {
var file = new Blob([response], {type: 'application/excel'});
var isChrome = !!window.chrome && !!window.chrome.webstore;
var isIE = /*#cc_on!#*/false || !!document.documentMode;
var isEdge = !isIE && !!window.StyleMedia;
if (isChrome){
var url = window.URL || window.webkitURL;
var downloadLink = angular.element('<a></a>');
downloadLink.attr('href',url.createObjectURL(file));
downloadLink.attr('target','_self');
downloadLink.attr('download', 'yourReports.xls');
downloadLink[0].click();
}
else if(isEdge || isIE){
window.navigator.msSaveOrOpenBlob(file,'yourReports.xls');
}
else {
var fileURL = URL.createObjectURL(file);
window.open(fileURL);
}
self.onXCELProcess = false;
},
function (error) {
console.error("error : "+error+" , error : "+JSON.stringify(error));
self.onXCELProcess = false;
}
)
}
function getXL(admin) {
return MotherService.callToServer({method: 'POST', url: URL + "orderxl", appMember: admin});
}
callToServer() method do request, with json body. and return the deferred.promise
for use of then.
server
#RequestMapping(value = "/"+Request.ADMIN_PATH+"/"+Request.ORDER_XL, method = RequestMethod.POST)
public void getFile(#RequestBody OrderXLRequest request, HttpServletResponse response) {
try {
File file = orderXLService.execute(request).getFile(); //get the file. already saved and ready to send
try{
InputStream inputStream = new FileInputStream(file);
String headerKey = "Content-Disposition";
String headerValue = String.format("attachment; filename=\"%s\"", "excelfilename.xlsx");
response.setHeader(headerKey, headerValue);
try {
FileCopyUtils.copy(inputStream, response.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
}catch(Exception e){
System.out.println("Exception in file download :"+e);
}
}catch (Exception e) {
e.printStackTrace();
}
}
thank you very much for any help or suggestion

How to pass Json array to WWWform as field in unity

I want to pass three field in wwwform, which contain two single value and a json array.
Here is my Json:
{
"Fname":"Abc",
"Lname":"Xyz",
"Marks": [{"MarksA":"23","MarksB":"65" },
{"MarksA":"24","MarksB":"56" } ]
}
My current code is
void Start()
{
WWWForm form = new WWWForm();
form.AddField("Fname", "Abc");
form.AddField("Lname", "Xyz");
//passing the array as string
string Mymarks = "[{\"MarksA\":\"23\",\"MarksB\":\"65\" },{\"MarksA\":\"24\",\"MarksB\":\"56\" } ]";
form.AddField("Marks", Mymarks);
WWW www = new WWW("Urltoservice", form);
StartCoroutine("PostRequest", www);
}
IEnumerator PostRequest(WWW www)
{
yield return www;
if (www.error == null)
{
Debug.Log("Session Saved");
}
else
{
Debug.Log("WWW Error: " + www.error);
}
}
But I am getting 500 internal server Error. Please help me.
Try using WWW instead of WWWForm
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using System.Collections.Generic;
public class SendData : MonoBehaviour {
void Start()
{
gameObject.GetComponent<Button>().onClick.AddListener(SendOnClick);
}
IEnumerator WaitForWWW(WWW www)
{
yield return www;
string txt = "";
if (string.IsNullOrEmpty(www.error))
txt = www.text; //text of success
else
txt = www.error; //error
GameObject.Find("TextDemo").GetComponent<Text>().text = "--------\n\n" + txt;
}
void SendOnClick()
{
try
{
GameObject.Find("TextDemo").GetComponent<Text>().text = "Starting..";
string ourPostData = "{\"MarksA\":\"23\",\"MarksB\":\"65\" },{\"MarksA\":\"24\",\"MarksB\":\"56\" }";
Dictionary<string,string> headers = new Dictionary<string, string>();
headers.Add("Content-Type", "application/json");
byte[] jData = System.Text.Encoding.ASCII.GetBytes(ourPostData.ToCharArray());
WWW api = new WWW("YOUR URL", jData, headers);
StartCoroutine(WaitForWWW(api));
}
catch (UnityException ex) { Debug.Log(ex.message); }
}
}

POST Requests on WP7

I've been dying for about 6 hours trying to figure out how to make a regular POST request in WP7 , I tried the answers of similar questions posted here and on many other places, I also tried many different APIs POST request, they all lead to one certain problem,
The remote server returned an error: NotFound.
it seems like everytime there's something missing.
So, if you please someone show us how to properly get a POST request right in this WP7
I use this to post to facebook without any problem:
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(requestUrl);
request.Method = "POST";
request.BeginGetResponse((e) =>
{
try
{
WebResponse response = request.EndGetResponse(e);
// Do Stuff
}
catch (WebException ex)
{
// Handle
}
catch (Exception ex)
{
// Handle
}
}, null);
I assume you would have tried this already so it may be something to do with the post data (which isn't in the above example as facebook uses the query string). Can you give us any more info?
EDIT: This is an (untested) example for writing post data:
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(requestUrl);
request.Method = "POST";
request.BeginGetRequestStream((e) =>
{
using (Stream stream = request.EndGetRequestStream(e))
{
// Write data to the request stream
}
request.BeginGetResponse((callback) =>
{
try
{
WebResponse response = request.EndGetResponse(callback);
// Do Stuff
}
catch (WebException ex)
{
// Handle
}
catch (Exception ex)
{
// Handle
}
}, null);
}, null);
I use the following class for making POST requests with WP7:
public class PostMultiPartFormData
{
private Dictionary<string, object> Parameters;
private Encoding ENCODING = Encoding.UTF8;
private string BOUNDARY = "-----------------------------wp7postrequest";
public event EventHandler PostComplete;
public void Post(string postbackURL,
Dictionary<string, object> parameters)
{
Parameters = parameters;
Uri url = null;
url = new Uri(postbackURL);
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.Method = "POST";
request.ContentType = "multipart/form-data; boundary=" + BOUNDARY;
request.BeginGetRequestStream(new AsyncCallback(SendStatusUpdate), request);
}
private void SendStatusUpdate(IAsyncResult ar)
{
HttpWebRequest request = (HttpWebRequest)ar.AsyncState;
Stream stream = request.EndGetRequestStream(ar);
byte[] byteArray = GetMultipartFormData(Parameters, BOUNDARY);
stream.Write(byteArray, 0, byteArray.Length);
stream.Close();
stream.Dispose();
request.BeginGetResponse(new AsyncCallback(StatusUpdateCompleted), request);
}
private byte[] GetMultipartFormData(Dictionary<string, object> postParameters, string boundary)
{
Stream formDataStream = new System.IO.MemoryStream();
foreach (var param in postParameters)
{
if (param.Value is byte[])
{
byte[] fileData = param.Value as byte[];
string header = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"; filename=\"{2}.jpg\";\r\nContent-Type: application/octet-stream\r\n\r\n", boundary, param.Key, param.Key);
formDataStream.Write(ENCODING.GetBytes(header), 0, header.Length);
formDataStream.Write(fileData, 0, fileData.Length);
}
else
{
string postData = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"\r\n\r\n{2}\r\n", boundary, param.Key, param.Value);
byte[] b = ENCODING.GetBytes(postData);
foreach (var item in b)
{
formDataStream.WriteByte(item);
}
}
}
string footer = "\r\n--" + boundary + "--\r\n";
byte[] footerbytes = ENCODING.GetBytes(footer);
formDataStream.Write(footerbytes, 0, footerbytes.Length);
formDataStream.Position = 0;
byte[] formData = new byte[formDataStream.Length];
formDataStream.Read(formData, 0, formData.Length);
formDataStream.Flush();
formDataStream.Close();
return formData;
}
private void StatusUpdateCompleted(IAsyncResult ar)
{
if (PostComplete != null)
{
PostComplete(ar, null);
}
}
}
Example:
PostMultiPartFormData postRequest = new PostMultiPartFormData();
postRequest.PostComplete += new EventHandler( (sender, e) =>
{
IAsyncResult ar = ((IAsyncResult)sender);
using (WebResponse resp = ((HttpWebRequest)ar.AsyncState).EndGetResponse(ar))
{
using (StreamReader sr = new StreamReader(resp.GetResponseStream()))
{
string responseString = sr.ReadToEnd();
this.Dispatcher.BeginInvoke(() =>
{
textBlock.Text = responseString;
});
}
}
});
postRequest.Post("http://localhost:50624/SSLProxy.ashx",
new Dictionary<string, object>() { { "param1", "value1" } });
This should work...
If it doesn't let me know! :-)
For easier access to advanced http features check out these http classes:
http://mytoolkit.codeplex.com/wikipage?title=Http
It encapsulates GET, POST, FILES (using path or Stream objects) and GZIP (not directly supported by WP7) requests.
To add post data just call BeginGetRequestStream method (also, BeginGetResponse move to GetRequestStreamCallback)
request.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), request);
void GetRequestStreamCallback(IAsyncResult asynchronousResult)
{
HttpWebRequest webRequest = (HttpWebRequest)asynchronousResult.AsyncState;
// End the stream request operation
Stream postStream = webRequest.EndGetRequestStream(asynchronousResult);
// Create the post data
string postData = "post data";
byte[] byteArray = Encoding.Unicode.GetBytes(postData);
// Add the post data to the web request
postStream.Write(byteArray, 0, byteArray.Length);
postStream.Close();
// Start the web request
webRequest.BeginGetResponse(new AsyncCallback(GetResponseCallback), webRequest);
}
I recommend you to use the postclient. It is pretty simple. You just need to add reference to dll file into your project, and then write something like:
public void authorize(string login, string password)
{
Dictionary<string, object> parameters = new Dictionary<string, object>();
parameters.Add("command", "login");
parameters.Add("username", login);
parameters.Add("password", password);
PostClient proxy = new PostClient(parameters);
proxy.DownloadStringCompleted += (sender, e) =>
{
if (e.Error == null)
{
MessageBox.Show(e.Result);
}
};
proxy.DownloadStringAsync(new Uri("http://address.com/service", UriKind.Absolute));
}

Google OAuth2.0 - Windows phone 7

Experts,
I'm new to OAuth,
I'm writing an small App in windows Phone 7, I'm using OAuth2 for google contacts, I need to get the initial URL API (1) to get the Token
1) https://accounts.google.com/o/oauth2/auth?response_type=code&scope=https://www.google.com/m8/feeds/&redirect_uri=REDIRECT_URI&client_id=CLIENT_ID&hl=en-US&from_login=1&as=NEW_AS&pli=1
I got the success code, and when I'm trying to use this
https://www.google.com/m8/feeds/contacts/default/full?access_token=TOKEN_CODE
but I'm getting 401 error back,
Can you please advice, what mistake i'm going.
I've taken Twitter OAuth example as base, and doing modifications.
CODE
var uri = new Uri(url);
var request = BuildOAuthWebRequest(url, null);
MakeGetRequest(callback, request);
private static HttpWebRequest BuildOAuthWebRequest( string url, string realm)
{
var header = new StringBuilder();
var request = (HttpWebRequest)WebRequest.Create(url);
return request;
}
private static void MakeGetRequest(EventHandler<OAuthEventArgs> callback, HttpWebRequest request)
{
var asyncState = request.BeginGetResponse(new AsyncCallback((asyncRes) =>
{
HttpWebResponse response = null;
try
{
//request has returned
response = (HttpWebResponse)request.EndGetResponse(asyncRes);
if (response.StatusCode == HttpStatusCode.OK)
{
using (StreamReader sr = new StreamReader(response.GetResponseStream()))
{
var token = sr.ReadToEnd();
callback(null, new OAuthEventArgs() { Response = token });
}
}
}
catch (WebException we)
{
string t = new StreamReader(we.Response.GetResponseStream()).ReadToEnd();
callback(null, new OAuthEventArgs() { Error = we, ErrorMessage = t, IsError = true });
}
catch (Exception e)
{
callback(null, new OAuthEventArgs() { Error = e, ErrorMessage = e.Message, IsError = true });
}
finally
{
if (response != null)
response.Close();
}
}), null);
}

Resources