ReadAsMultipartAsync returns error when no file provided - asp.net-mvc-4

I think my code was working previously with this same code
var streamProvider = new CustomMultipartFormDataStreamProvider(path);
// Upload media
await Request.Content.ReadAsMultipartAsync(streamProvider);
but now it gives System.InvalidOperationException error:
Access to the path 'C:\xxx\Projects\Test Projects\CL.MiClaim\CL.MiClaim\uploads' is denied.
When I provide a file for upload then it works al right. This below doesn't work (since it hasn't yet read the request content yet??)
if (streamProvider.FileData.Count > 0)
{
}
any help will be appreciated.
Note: example code can be found at:
http://www.asp.net/web-api/overview/working-with-http/sending-html-form-data,-part-2

Related

react-apollo Error: Network error: Unexpected token < in JSON at position 1

I want to send a request to this server via Apollo and get a query :
const client = new ApolloClient({
link: new HttpLink({
uri:'http://mfapat.com/graphql/mfaapp/'}),
cache: new InMemoryCache()
})
const FeedQuery = gql
query{
allFmr{
fmrId,
name,
studio,
bedRm1,
bedRm2,
bedRm3,
bedRm4
}
}
`
But I'm facing this error message:
Unhandled (in react-apollo:Apollo(FMRScreen)) Error: Network error: Unexpected token < in JSON at position 1
at new ApolloError (http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:109336:32)
at ObservableQuery.currentResult (http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:109447:28)
at GraphQL.dataForChild (http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:103192:66)
at GraphQL.render (http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:103243:37)
....
But I can easily open "http://mfapat.com/graphql/mfaapp/" in my browser and get a query. Does anyone know where the problem is?
Right now, Apollo treats everything sent from the server as JSON. However, if there is an error, then your server might be sending HTML to show a basic error page.
To see the error, open your dev tools, and look at the network tab. This shows an example 401 error:
As you can see, if you were to parse this as JSON you would stumble over the first character: < which is where our error message comes from.
Reading the specific error sent enables you to fix the bug.
To fix the general error, configure your server to send JSON on HTTP errors, not HTML code. This should allow Apollo to parse it and display a sensible error page.
EDIT: Also see this discussion - hopefully they will change the default Apollo behavior, or at least provide useful discussion.
Base on #eedrah answer, I managed to resolve this issue by using an error handler middleware to always return erros as JSONs, so that Apollo Client error link can parse the errors.
// On Apollo server
// Error handler
const errorHandler = (err, req, res, next) => {
if (res.headersSent) {
return next(err);
}
const { status } = err;
res.status(status).json(err);
};
app.use(errorHandler);

Cordova FileTransfer Plugin error code 1 for image upload

I am trying to take a picture on my phonegap app and then use the FileTransfer plugin to upload it to my server. I am getting error code 1 but there is no other explanation - this is VERY frustrating. I have scoured every piece of documentation and blog known to man with no luck.
I am using a basic LAMP server and it continues to give me an http 500 code. I am 99.9% sure this error is specific to my server because I have tested this with a different web server of mine and the code works fine. Here is the response:
{"code":1,"source":"file:///storage/emulated/0/Android/data/io.cordova.xxappxx/cache/1477607161788.jpg","target":"https://server.com/php/uploadPhoto.php","http_status":500,"body":"\t","exception":"https://server.com/php/uploadPhoto.php"}
Below is my front-end js code:
function uploadPhoto(imageURI) {
var options = new FileUploadOptions();
options.fileKey="file";
options.fileName=imageURI.substr(imageURI.lastIndexOf('/')+1);
alert(options.fileName);
options.mimeType="image/jpeg";
var params = {};
params.value1 = sessionStorage.getItem("token");
options.params = params;
options.chunkedMode = false;
options.headers = {Connection: "close"};
var ft = new FileTransfer();
ft.upload(imageURI, "https://servername.com/php/uploadPhoto.php", function(result){
console.log(JSON.stringify(result));
}, function(error){
console.log(JSON.stringify(error));
}, options, true);
}
And here is my back-end PHP code that is being called (uploadPhoto.php):
<?php
session_start();
header('Access-Control-Allow-Origin : *');
$new_image_name = "$userId.jpg";
move_uploaded_file($_FILES["file"]["tmp_name"], "/var/img/".$new_image_name);
?>
This ended up being an issue of image size. I was working on this project for a university and their servers have lots of security installed - one of these security configurations had a very small file upload size limit which was blocking the uploads. I discovered this by scanning some of the log files in the /var/log/ directory.

Google Apps Script: Salesforce API Call

Just finished breakfast and already hit a snag. I'm trying to call the salesforce REST api from my google sheets. I've written a working script locally in python, but converting it into JS, something went wrong:
function authenticateSF(){
var url = 'https://login.salesforce.com/services/oauth2/token';
var options = {
grant_type:'password',
client_id:'XXXXXXXXXXX',
client_secret:'111111111111',
username:'ITSME#smee.com',
password:'smee'
};
var results = UrlFetchApp.fetch(url, options);
}
Here is the error response:
Request failed for https://login.salesforce.com/services/oauth2/token
returned code 400. Truncated server response:
{"error_description":"grant type not
supported","error":"unsupported_grant_type"} (use muteHttpExceptions
option to examine full response) (line 12, file "Code")
Mind you, these exact parameters work fine in my local python script (putting the key values inside quotations).
Here are the relevant docs:
Google Script: Connecting to external API's
Salesforce: REST API guide
Thank you all!
Google's UrlFetchApp object automatically defaults to a GET request. To authenticate, you have to explicitly set in the options the method "post":
function authenticateSF(){
var url = 'https://login.salesforce.com/services/oauth2/token';
var payload = {
'grant_type':'password',
'client_id':'XXXXXXXXXXX',
'client_secret':'111111111111',
'username':'ITSME#smee.com',
'password':'smee'
};
var options = {
'method':'post',
'payload':payload
};
var results = UrlFetchApp.fetch(url, options);
}

Opening local html file with SlimerJS

I have a script that works in PhantomJS but I'm trying to switch to SlimerJS. I keep getting an error when trying to open a local file:
var webPage = require('webpage');
var system = require('system');
var page = webPage.create();
page.viewportSize = { width: 2048, height: 1536 };
console.log('Processing',system.args[1]);
page.open(
'simple.html',
function start(status) {
setTimeout(function(){
page.render(system.args[2], {format: 'png'});
phantom.exit();
},1000);
}
);
simple.html is a file located in the same directory as the script. The resulting PNG says "Address Not Found", "simple.html could not be found. Please check the name and try again."
I've also tried:
full OS path, eg /User/blah/blah/simple.html
file URI file:///Users/blah/blah/simple.html
These yield a similar result.
I'd rather not have the script publicly available for a variety of reasons. Is it possible to launch a local file with SlimerJS?
I don't think its possible. Reading the docs it specifies a url.
I got around this by running a http server
python -m SimpleHTTPServer
Then accessing it through localhost.
page.open('http://localhost:8000/simple.html',...)
A file URI does work. Something like file:///Users/name/project/file.html.

CakePHP 2.0 + Notice (8): Undefined index: Upload [APP/Controller/UploadsController.php, line 32]

Im using 000webhost as a way to host my portfolio of websites. However Im getting this error thrown in which doesn't happen to me on localhost.
Notice (8): Undefined index: Upload [APP/Controller/UploadsController.php, line 32]
This is the code it seems to be referring to,
public function add() {
$this->render();
if($this->request->is('post')){
$file = $this->request->data['Upload']['file'];
if($this->Upload->save($this->data) && move_uploaded_file($file['tmp_name'],APP.'webroot/files/uploads'.DS.$this->Upload->id.'.mp4'))
{
$this->Session->setFlash('<p class="uploadflash">The upload has been saved</p>', true);
$this->redirect(array('controller'=>'Uploads', 'action' => 'watch', $this->Upload->id));
} else {
$this->Session->setFlash('<p class="loginerror">The upload could not be saved, mp4 files can be saved only.</p>', true);
}
}
}
Any ideas as to why this is happening?
Also in addition my Elements are not showing up on this online hosting either?
I get thrown this error on the page
Element Not Found: Elements/uploads/recentuploads.ctp
Does anyone else seem to have this problem??
Upon further inspection I have found that the server does not allow file upload sizes to exceed 2mb, in this instance PHP throws the error above.