Current request is not a multipart request Springboot+ angular js - angularjs

I could not figure out the problem for days now. can any one help me? I think the problem is in the backend I also created a custom directive for the angular
this is springbot controller
#RequestMapping(value = "/add", method = RequestMethod.POST,consumes= {MediaType.APPLICATION_JSON_VALUE,MediaType.MULTIPART_FORM_DATA_VALUE} )
public ResponseEntity <AGPResponse>addArtist( #RequestParam("file") MultipartFile file, #RequestBody ArtistModel Ar ) {
try {
if (Ar.getId() == null) {
byte[] bytes = file.getBytes();
BufferedOutputStream stream =
new BufferedOutputStream(new FileOutputStream(new File("-uploaded")));
stream.write(bytes);
stream.close();
service.addArtist(Ar);}
else {
service.updateArtist(Ar);
}
} catch (Exception e) {
return AGPResponse.error(getMessage("something went Wrong"), HttpStatus.UNPROCESSABLE_ENTITY);
}
return AGPResponse.success(getMessage("successful"));
}
this is angular js controller
APP.controller('ArtistController', artistcontroller);
function artistcontroller($rootScope, $scope, ArtistService, $routeParams,
$route) {
$scope.user={
name:"",
nickname:"",
file:[]
}
$scope.saveArtist=function(datas){
var data=new FormData();
data.append("name",$scope.user.name);
data.append("nickname",$scope.user.nickname);
for(i=0;i<$scope.user.file.length;i++){
data.append("file",$scope.user.file[i]);
}var config={
transformRequest:angular.identity,
transformResponse:angular.identity,
headers:{'Content-Type':undefined}
}
ArtistService.saveArtist.save(datas, sucess, error);
function sucess(obj) {
$scope.successMessage = "Saved!"
$scope.errors = null;
}
function error(obj) {
$scope.successMessage = null;
$scope.errors = obj;
}}}

Related

err_connection_timed_out after some successful calls in angularjs

I am using http service of AngularJs and it works successfully. But from last three months, I receive err_connection_timed_out after 1 or two successful calls. If I reload the page, then the error disappears.
I am using ASP.Net MVC as backend application and it uses Cookies for session management.
Anybody can help how to resolve this issue?
Global.asax.cs
protected void Application_BeginRequest(Object sender, EventArgs e)
{
HttpContext.Current.Items["dbkey"] = new DBEntities();
}
protected void Application_BeginRequest(Object sender, EventArgs e)
{
var entityContext = HttpContext.Current.Items["dbkey"] as DBEntities;
if (entityContext != null)
entityContext.Dispose();
}
LoginController
public JsonResult JsonLogin(string email, string password)
{
// Hashed ticket
string hashCookies = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hashCookies);
cookie.Expires = expiryDate;
Response.Cookies.Add(cookie);
HttpCookie mycookie = new HttpCookie("cookieName");
HttpContext.Current.Response.Cookies.Set(mycookie);
}
StaffController
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
HttpCookie cookie = HttpContext.Current.Request.Cookies["cookieName"];
if (cookie == null || string.IsNullOrEmpty(User.Identity.Name))
{
filterContext.Result = new RedirectResult("/Login/Index");
}
base.OnActionExecuting(filterContext);
}
public JsonResult GetData()
{
var res = entityContext.StaffData.Where(...).ToList();
return Json(res, JsonRequestBehavior.AllowGet);
}
Data.js
var app = angular.module('StaffApp', []);
app.controller('StaffCtrl', function ($scope, $http) {
$scope.GetData = function () {
$http.get("/Staff/GetData")
.then(function (response) {
let data = response.data;
if (data.length > 0) {
angular.forEach(data, function (fm, key) {
$scope.Staffs.push(fm);
});
}
}, function (response) {
});
};

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

ng-flow file upload in web api

I have seen many examples with ng-flow having the php side server to upload the files. But as I am not an expert in php and I need some help in the webapi, can someone please help me to find a working example or tutorial of ng-flow with webapi files upload.
Thanks everyone.
below is my web-api code to do this
[HttpPost]
public async Task<HttpResponseMessage> SaveFile()
{
if (!Request.Content.IsMimeMultipartContent())
Request.CreateResponse(HttpStatusCode.UnsupportedMediaType);
var provider = FileSaver.GetMultipartProvider();
var result = await Request.Content.ReadAsMultipartAsync(provider);
var fileInfo = FileSaver.MoveToTemp(result);
return Request.CreateResponse(HttpStatusCode.OK, fileInfo);
}
it uses the custom FileSaver class
public class FileSaver
{
public static MultipartFormDataStreamProvider GetMultipartProvider()
{
var uploadFolder = //your upload path;
return new MultipartFormDataStreamProvider(uploadFolder);
}
private static string GetDeserializedFileName(MultipartFileData fileData)
{
var fileName = GetFileName(fileData);
return JsonConvert.DeserializeObject(fileName).ToString();
}
private static string GetFileName(MultipartFileData fileData)
{
return fileData.Headers.ContentDisposition.FileName;
}
public static FileInfo MoveToTemp(MultipartFormDataStreamProvider result)
{
var originalFileName = GetDeserializedFileName(result.FileData.First());
var uploadedFileInfo = new FileInfo(result.FileData.First().LocalFileName);
string timestamp = DateTime.UtcNow.ToString("yyyyMMddHHmmssfff", CultureInfo.InvariantCulture);
var folder = Directory.CreateDirectory(**); //your upload path
if (!folder.Exists) folder.Create();
var filename = folder.FullName + #"\" + originalFileName;
MoveFile(uploadedFileInfo, filename);
return uploadedFileInfo;
}
private static void MoveFile(FileInfo fileInfo, string filename)
{
var count = 0;
do
{
try
{
fileInfo.MoveTo(filename);
return;
}
catch (Exception)
{
if (count == 4)
{
throw;
}
count++;
Thread.Sleep(1 * 1000);
}
} while (true);
}
}

upload file from phonegap camera to .Net web api

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

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