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)
};
}
}
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
I am unable to get a json response from my controller action. The network shows as a post which is correct as I am posting a file to the server, however, needs a JSON response sent back to my view.
public JsonResult Upload(HttpPostedFileBase file, int id)
{
Homes thishomes= _db.Homes.FirstOrDefault(t => t.Id == id);
FileUploader fileupload = new FileUploader();
fileupload.PostIt(file.InputStream);
return Json(new { success = true, response = "File uploaded.", JsonRequestBehavior.AllowGet });
}
JQUERY using Dropzonejs:
Dropzone.options.DropzoneForm = {
paramName: "file",
maxFilesize: 2000,
maxFiles: 28,
dictMaxFilesExceeded: "Custom max files msg",
init: function () {
this.on("success", function () {
alert("Added file");
})
}
};
Can anyone see an this issue?
Try to write [HttpPost] attribute over your action. Also "The network shows as a post which is correct" if its post then you don't need JsonRequestBehavior.AllowGet
when you are returning Json to your request
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.
I was just curious, is it possible to have direct network transfers in c#, without local caching.
e.g.
I have response stream which represents GoogleDrive file and request stream to upload file to another GoogleDrive account.
At that momment I can download file to local pc and next upload it to the google drive. But is it possible to upload it directly from one google drive to another or, at least, start uploading before full download will be completed.
Thank
Yes you can, with Google Drive api you download file into a stream and you keep it in memory so you can upload it to another google drive account after login.
You get your token on first account and download a file keeping it in a stream.
THen you authenticate on other google drive account and upload the file using the stream.
PS: When you are inserting the file on the second drive account, instead of getting
the byte[] array reading the file from disk you get the byte array from the stream you have in memory.
File Download Example:
public static System.IO.Stream DownloadFile(
IAuthenticator authenticator, File file) {
if (!String.IsNullOrEmpty(file.DownloadUrl)) {
try {
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(
new Uri(file.DownloadUrl));
authenticator.ApplyAuthenticationToRequest(request);
HttpWebResponse response = (HttpWebResponse) request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK) {
return response.GetResponseStream();
} else {
Console.WriteLine(
"An error occurred: " + response.StatusDescription);
return null;
}
} catch (Exception e) {
Console.WriteLine("An error occurred: " + e.Message);
return null;
}
} else {
// The file doesn't have any content stored on Drive.
return null;
}
File insert example:
private static File insertFile(DriveService service, String title, String description, String parentId, String mimeType, String filename) {
// File's metadata.
File body = new File();
body.Title = title;
body.Description = description;
body.MimeType = mimeType;
// Set the parent folder.
if (!String.IsNullOrEmpty(parentId)) {
body.Parents = new List<ParentReference>()
{new ParentReference() {Id = parentId}};
}
// File's content.
byte[] byteArray = System.IO.File.ReadAllBytes(filename);
MemoryStream stream = new MemoryStream(byteArray);
try {
FilesResource.InsertMediaUpload request = service.Files.Insert(body, stream, mimeType);
request.Upload();
File file = request.ResponseBody;
// Uncomment the following line to print the File ID.
// Console.WriteLine("File ID: " + file.Id);
return file;
} catch (Exception e) {
Console.WriteLine("An error occurred: " + e.Message);
return null;
}
}
I have a script in which on Click on link i need to download PDF file present in temp folder on server and this i am doing it by calling AJAX function. that AJAX function is calling struts 2 action method which is reading content of the file and write it to output stream.
and now problem is if that file is not present in temp folder. that is throwing exception. so i decided to handle it by using json. if that file exist in temp folder. i am mapping the key to
jsonObject.put("exist", true)
and if that file does not exist in temp folder. i am mapping the key to
jsonObject.put("exist", false)
and in struts.xml i am handling the action by with this way
<action name="DisplayStaticPdf"
class="com.ui.DisplayStaticPdfAction">
<result name="success" type="json"/>
</action>
and in script i am handling it through this way
function downloadDoc(actionName){
$.ajax({
url: actionName,
type: 'post',
dataType: 'json',
error: function(data) {
if(data.exist!= null && data.exist == 'false'){
alert('The document you are trying to download does not exist at location. Please make sure file exist .');
}
},
success: function() {
}
});
}
and when file is not present, it is showing me the same alert. but when file is not present, it does nothing and does not download the pdf present in temp folder.
my action class looks like ->
String pdfFileName = null;
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
String rawFileName = "abc.pdf";
String returnString = "fileNotExist";
jsonObject = new JSONObject();
ServletOutputStream out = response.getOutputStream();
response.setContentType("application/pdf");
URL url = new URL(fileURL);
URLConnection conn = url.openConnection();
if (conn.getContentLength() != 0 && conn.getContentLength() != -1)
{
bis = new BufferedInputStream(conn.getInputStream());
bos = new BufferedOutputStream(out);
try
{
byte[] buff = new byte[2048];
int bytesRead;
while (-1 != (bytesRead = bis.read(buff, 0, buff.length)))
{
bos.write(buff, 0, bytesRead);
}
jsonObject.put("exist", true);
}
returnString = SUCCESS;
}
else
{
jsonObject.put("exist", false);
returnString ="fileNotExist";
}
return returnString;
hope you guys understand my issue. Anybody please put light on this whether i am doing it in right approach. or is there is any other easy way to do it
Thanks,
Ankit