Angular service.ts:
getExcel() {
let link: string = (this.url);
return link;
}
component.ts:
public getExcel() {
//checks if string is empty, undefined or not null
if (this.langCode) {
return window.open(this.avrs.getExcel());
}
}
Java rest.java
#GET
#Path("/excel")
#Produces("application/vnd.ms-excel")
public Response getTransportCostsExcel(
#Context HttpServletRequest request,
) {
byte[] excelInBytes = excelGen.getExcel();
if(excelInBytes == null){
return Response.status(Response.Status.NOT_FOUND).entity("No data").build();
}
//Header details
String contentType = "application/vnd.ms-excel";
Response.ResponseBuilder responseBuilder = javax.ws.rs.core.Response.ok((Object) excelInBytes);
responseBuilder.type(contentType);
responseBuilder.header("Content-Disposition", "attachment; filename=" + fileName);
//Returns Excel
return responseBuilder.build();
}
When I try calling my api from postman i get "No data" and status is 401 not found. So the rest method works fine.
I get my excel file if data is found. But I can't seem to handle the 401 response. Angular opens a new window and says
site not avaliable: ERR_INVALID_RESPONSE
As you can see im not using http.get cause I want the user to start downloading the excel if the file is found.
Related
im trying to send json parameter to asp request handler like this:
$scope.SaveCarUpgrades = function () {
var parameter = JSON.stringify(resultCarUpgrades);
$http.get("/ProfileEditor/saveUserCarUpgrades/" + $scope.useridCarUpgrades,
{ params: { name: parameter }}
).then(onsuccess, onfail);
function onsuccess(response) {
if (response.status == 200) {
$scope.saveUpgradesResult = "save upgrades success";
} else {
$scope.saveUpgradesResult = "save upgrades failed" + response.status;
}
}
function onfail(response) {
$scope.saveUpgradesResult = "save upgrades failed" + response.status;
// $scope.saveUpgradesResult = parameter;
}
}
c# request handler is something very simpe. its just for testing right now:
public string SaveUserCarUpgrades(string id)
{
string result = id;
var data = Request.QueryString["name"];
return id;
}
the problem is i always get 404 if if use json as parameter. (its a complex long json) but as simple json or simple string the response is fine. i dont think the problem is mime type as i set it in iis express in devcmd.
thank you for helping
My REST API which has been written in SpringBoot has following method for the purpose of uploading a photo.
#RequestMapping(method = RequestMethod.POST, value = "/save-photo")
public ResponseEntity<?> uploadPhoto(#RequestPart("file") MultipartFile file){
if (file.isEmpty()) {
System.out.println("Attached file is empty");
ErrorResponse errorResponse = new ErrorResponse();
errorResponse.setMessage("Attached file is empty");
return new ResponseEntity<ErrorResponse>(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
}
String returnPath = null;
try {
byte[] bytes = file.getBytes();
String saveDate = new SimpleDateFormat("yyMMddHHmmssSSS").format(new Date());
Path path = Paths.get(UPLOAD_FOLDER + saveDate + "___" + file.getOriginalFilename());
Files.write(path, bytes);
returnPath = String.valueOf(path);
} catch (IOException e) {
//e.printStackTrace();
ErrorResponse errorResponse = new ErrorResponse();
errorResponse.setMessage(e.getMessage());
return new ResponseEntity<ErrorResponse> (errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
}
System.out.println("Before returning, return path = "+returnPath);
return new ResponseEntity<String>(returnPath, HttpStatus.OK);
}
Following is the code I have written to call the above method.
savePhoto(photoToSave: File) {
let formData: FormData = new FormData();
formData.append("file", photoToSave);
let savedPath = this._http
.post(this._endpointUrl + "/save-photo", formData)
.map(
res => {
return res.json();
}
)
.catch(handleError);
return savedPath;
}
File uploading process is fine. But Angular2 gives me the following error.
Unexpected token F in JSON at position 0
Note that the F is the starting letter of the path the server returns.
Why this happens? I think the server response is not a JSON. But why? Usually RestControllers return JSON. All other controller methods in my server works fine.
How to resolve this?
Response Captured from Browser console
Header:
Access-Control-Allow-Credentials:true
Access-Control-Allow-Origin:http://localhost:3000
Content-Length:88
Content-Type:application/json;charset=UTF-8
Date:Fri, 26 May 2017 04:33:05 GMT
Vary:Origin
Response:
F:\Work\Images\170526100305388___2.jpg
EDIT
Screen shots from the brwoser
Response:
Posting as a answer the workaround I used to get over the issue. Hope it might help somebody.
What I did was instead of returning a String ResponseEntity, I created a JSON object which encapsulates the string I want to return and returned as the response.
JSONObject obj = new JSONObject();
obj.put("savedPath", returnPath);
return new ResponseEntity<>(obj, HttpStatus.OK);
In the front end, I just return the response.json()
let savedPath = this._http
.post(this._endpointUrl + "tender/save-new/save-photo", formData)
.map(
res => {
return res.json();
}
)
.catch(handleError);
Now in the controller class, I can access the saved path in following way.
this._tendersService.savePhoto(files[0])
.subscribe(res => {
console.log("saved path = " + res.savedPath);
}
);
I'm using oAuth 2.0 in ASP.NET web API.
In refresh token provider class I have code like this.
public Task ReceiveAsync(AuthenticationTokenReceiveContext context)
{
string tokenId = context.Token;
var protectedTicket = WebApiBusiness.GetProtectedTicket(tokenId);
if (!string.IsNullOrEmpty(protectedTicket))
{
context.DeserializeTicket(protectedTicket);
var result = WebApiBusiness.RemoveRefreshToken(tokenId);
}
else
{
context.Response.ContentLength = 200;
context.Response.ContentType = "application/json";
var ML_DefaultRes = new ML_DefaultRes()
{
ResponseCode = ResponseCodes.TokenInvalidRC,
APIVersion = apiversion,
ErrorDescription = ResponseCodes.GetRCDescription(ResponseCodes.TokenInvalidRC)
};
string str = JsonConvert.SerializeObject(ML_DefaultRes);
context.Response.Write(str);
return;
}
}
When refresh token is not valid I want custom response in JSON format.
But instead of setting content length to 200 it is taking content length upto 25 only, which makes invalid JSON response.
Is their any way to make this happen?
I'm trying to return text to a message box when an error occurs and the return type is JsonResult.
I believe I'm returning a valid type, but when the messagebox appears, it says "undefined".
I have the Json set up as the following:
string maxChars = "Upload file size exceeded!";
return Json(new { MaxCharacters = maxChars });
What am I doing wrong?
If you are returning this json data from an HttpGet action method, you should explicitly tell the Json method to allow sending back the json data for a GET request.
public ActionResult YourMethod()
{
string maxChars = "Upload file size exceeded!";
return Json(new { MaxCharacters = maxChars }, JsonRequestBehavior.AllowGet);
}
And in your client side code, you should be accessing the MaxCharacters property of the response coming back from the ajax call.
$.get("#url.Action("YourMethod","YourControllerName")",function(res){
alert(res.MaxCharacters);
});
In my site, i gave download option to download the file. when i am checking in local server it is working properly. But after deploy the server, if i click the link means it will show the following error,
This request has been blocked because sensitive information could be disclosed to third party web sites when this is used in a GET request. To allow GET requests, set JsonRequestBehavior to AllowGet.
My code here
public ActionResult Download(string fileName)
{
string pfn = Server.MapPath("~/Content/Files/" + fileName);
if (!System.IO.File.Exists(pfn))
{
//throw new ArgumentException("Invalid file name or file not exists!");
return Json(new JsonActionResult { Success = false, Message = "Invalid file name or file not exists!" });
}
else
{
return new BinaryContentResult()
{
FileName = fileName,
ContentType = "application/octet-stream",
Content = System.IO.File.ReadAllBytes(pfn)
};
}
}
This is my code. I don't know what mistake here, Can anyone find my problem and tell me ?
The Problem with ur code is that u r missing 'JsonRequestBehavior.AllowGet' while returning json.
public ActionResult Download(string fileName)
{
string pfn = Server.MapPath("~/Content/Files/" + fileName);
if (!System.IO.File.Exists(pfn))
{
//throw new ArgumentException("Invalid file name or file not exists!");
return Json(new JsonActionResult { Success = false, Message = "Invalid file name or file not exists!" },JsonRequestBehavior.AllowGet });
}
else
{
return new BinaryContentResult()
{
FileName = fileName,
ContentType = "application/octet-stream",
Content = System.IO.File.ReadAllBytes(pfn)
};
}
}