while trying uploaing nothing is happening - file-upload

i want to upload a file by node.js so i try by this article.
http://debuggable.com/posts/parsing-file-uploads-at-500-mb-s-with-node-js:4c03862e-351c-4faa-bb67-4365cbdd56cb
I run this code
var formidable = require('formidable')
, http = require('http')
, sys = require('sys');
var server=http.createServer(function(req, res) {
console.log('out if condition'+sys.inspect(req));
if (req.url == '/upload' && req.method.toLowerCase() == 'post') {
// parse a file upload
console.log('in if condition');
var form = new formidable.IncomingForm();
form.parse(req, function(fields, files) {
res.writeHead(200, {'content-type': 'text/plain'});
res.write('received upload:\n\n');
res.end(sys.inspect({fields: fields, files: files}));
});
return;
}
// show a file upload form
res.writeHead(200, {'content-type': 'text/html'});
res.end
( '<form action="/upload" enctype="multipart/form-data" method="post">'
+ '<input type="text" name="title"><br>'
+ '<input type="file" name="upload" multiple="multiple"><br>'
+ '<input type="submit" value="Upload">'
+ '</form>'
);
});
server.listen(8000);
when i upload the file it doesn't proceed further easily and doesn't go in if condition of upload why ?

fs.writeFile(files.upload.name, files.upload,'utf8', function (err) {
if (err) throw err;
console.log('It\'s saved!');
});
Please check.
http://rahulmehta1.wordpress.com/2011/04/26/uploading-a-file-in-node-js-by-formidable/

Related

Virtual Image Path not visible in partial View

bit of a weird one here. I tried finding an answer, but was unable to. New to node.
Problem: My virtual image paths work in my views, but not in my partial view, being the navbar. This navbar has a searchbar, and it is fetching the succulent plants in the db, with the following code:
let searchBar = document.getElementById("searchBar");
searchBar.addEventListener("keyup", searchDatabase);
function searchDatabase() {
const searchResults = document.getElementById("searchResults");
//Reg expressions prevent special characters and only spaces fetching from db
let match = searchBar.value.match(/^[a-zA-Z ]*/);
let match2 = searchBar.value.match(/\s*/);
if (match2[0] === searchBar.value) {
searchResults.innerHTML = "";
return;
}
if (match[0] === searchBar.value) {
fetch("searchSucculents", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ payload: searchBar.value }),
})
.then((res) => res.json())
.then((data) => {
let payload = data.payload;
searchResults.innerHTML = "";
if (payload.length < 1) {
searchResults.innerHTML = "<p>No search results found</p>";
return;
} else if (searchBar.value === "") {
searchResults.innerHTML = "";
return;
} else {
payload.forEach((item, index) => {
if (index > 0) {
searchResults.innerHTML += "<hr>";
}
searchResults.innerHTML +=
`<div class="card" style="width: 18rem;">
<img src="${item.SucculentImagePath}" class="card-img-top" alt="${item.SucculentName}">
<div class="card-body">
<p class="card-text">${item.SucculentName}</p>
</div>
</div>`;
});
}
return;
});
}
searchResults.innerHTML = "";
}
Here is the route:
app.post("/searchSucculents", async (req, res) => {
let payload = req.body.payload.trim();
let search = await Succulent.find({SucculentName: {$regex: new RegExp("^"+payload+".*","i")}}).exec();
//Limit Search Results to 10
search = search.slice(0, 10);
res.send({payload: search});
})
Here's the part in my schema defining the image path:
succulentSchema.virtual('SucculentImagePath').get(function() {
if (this.SucculentImage != null && this.SucculentImageType != null) {
return `data:${this.SucculentImageType};charset=utf-8;base64,${this.SucculentImage.toString('base64')}`
}
})
I'm able to reference this image path in my full views, as follows:
<img src="<%= succulent.SucculentImagePath %>">
However, when I try to access the SucculentImagePath attribute in this searchbar in my nav, it is undefined. Am I missing something here?
After doing further research, I discovered that you cant use mongoose virtuals when parsing data to JSON (noob mistake, I know).
I fixed it, by adding this as an option in the schema object:
toJSON: { virtuals: true } })

StreetView Publish API JavaScript Upload photo

I am trying to upload a photo from JavaScript using the StreetView Publish API and it seems that everything i try fails ... currently i have the uploadUrl and i need to make a post request with the actual image data
this is that i ended up doing
var input = document.querySelector('input[type="file"]').files;
var reader = new FileReader();
reader.onload = function(){
var dataURL = reader.result;
var xhr = new XMLHttpRequest();
xhr.open("POST", window.uploadUrl, true);
xhr.setRequestHeader("Authorization", gapi.client.getToken().token_type + ' ' + gapi.client.getToken().access_token);
xhr.setRequestHeader("Content-Type", "image/jpeg");
xhr.setRequestHeader("X-Goog-Upload-Protocol", "raw");
xhr.setRequestHeader("X-Goog-Upload-Content-Length", dataURL.length );
xhr.onreadystatechange = function() {//Call a function when the state changes.
if(xhr.readyState == XMLHttpRequest.DONE && xhr.status == 200) {
console.log(xhr);
}
}
xhr.send(dataURL);
};
reader.readAsDataURL(input[0]);
the answer i get is the following one:
Failed to load
https://streetviewpublish.googleapis.com/media/user/.../photo/...:
Response for preflight is invalid (redirect)
can anyone suggest any possible solution to this?
thanks
UPDATE
from what i see ... when i am trying to upload the image, 2 requests are generated ... both are OPTIONS and 302 status and none of them have the headers i am trying to send ... mainly the access token
var xhr = new XMLHttpRequest();
xhr.open("POST", window.uploadUrl + "?key=...", true);
xhr.setRequestHeader("Authorization", gapi.client.getToken().token_type + ' ' + gapi.client.getToken().access_token);
xhr.setRequestHeader("Authorization", gapi.client.getToken().access_token);
xhr.setRequestHeader("Content-Type", 'image/jpeg');
xhr.setRequestHeader("X-Goog-Upload-Protocol", "raw");
xhr.setRequestHeader("X-Goog-Upload-Content-Length", dataURL.length );
xhr.onreadystatechange = function() {
if(xhr.readyState == XMLHttpRequest.DONE && xhr.status == 200) {
console.log(xhr);
}
}
xhr.send(dataURL);

File upload using dropzon.js

I'm trying to upload files using dropzone.js
View:
#using (Html.BeginForm("SaveMethod", "ControllerName", FormMethod.Post, new { enctype = "multipart/form-data", #class = "dropzone", id = "js-upload-form" }))
........................
<div class="form-inline">
<div class="form-group">
<input type="file" name="MainFile" id="js-upload-files"/>
</div>
<div class="upload-drop-zone" id="drop-zone">
Just drag and drop files here
</div>
<div class="dropzone-previews"></div>
</div>
JS:
var formData = null;
formData = new FormData($form[0]);
dropZone.ondrop = function (e) {
e.preventDefault();
this.className = 'upload-drop-zone';
startUpload(e.dataTransfer.files)
}
dropZone.ondragover = function () {
this.className = 'upload-drop-zone drop';
return false;
}
dropZone.ondragleave = function () {
this.className = 'upload-drop-zone';
return false;
}
var startUpload = function (files) {
for (var i = 0; i < files.length; i++) {
formData.append(files[i].name, files[i]);
}
}
Controller:
[HttpPost]
public JsonResult SaveMethod(TaskManage objTaskManage, HttpPostedFileBase files)
{
}
Now, after submit, i want to have files that was dropped on drop area along with the files attached in upload control. Here, what happens is files giving me null and when i use Request.Files["MainFile"] i get only the files dropped on dropzone area, it doesn't show me the file i have upload to control.
I'm not able to find out the issue. Any help is really appreciated.
File upload in ASP.NET MVC using Dropzone JS and HTML5
You can download the latest version from the official site here http://www.dropzonejs.com/ and also we can install using the nuget package manage console by the following command Package Manager Console
PM> Install-Package dropzone
Now create a bundle for your script file in BundleConfig.cs
bundles.Add(new ScriptBundle("~/bundles/dropzonescripts").Include(
"~/Scripts/dropzone/dropzone.js"));
Similarly add the dropzone stylesheet in the BundleConfig.cs
bundles.Add(new StyleBundle("~/Content/dropzonescss").Include(
"~/Scripts/dropzone/css/basic.css",
"~/Scripts/dropzone/css/dropzone.css"));
Now add the bundle reference in your _Layout page
View Page:
<div class="jumbotron">
<form action="~/Home/SaveUploadedFile" method="post" enctype="multipart/form-data" class="dropzone" id="dropzoneForm" style="width: 50px; background: none; border: none;">
<div class="fallback">
<input name="file" type="file" multiple />
<input type="submit" value="Upload" />
</div>
</form>
</div>
Controller:
public ActionResult SaveUploadedFile()
{
bool isSavedSuccessfully = true;
string fName = "";
try{
foreach (string fileName in Request.Files)
{
HttpPostedFileBase file = Request.Files[fileName];
//Save file content goes here
fName = file.FileName;
if (file != null && file.ContentLength > 0)
{
var originalDirectory = new DirectoryInfo(string.Format("{0}Images\\WallImages", Server.MapPath(#"\")));
string pathString = System.IO.Path.Combine(originalDirectory.ToString(), "imagepath");
var fileName1 = Path.GetFileName(file.FileName);
bool isExists = System.IO.Directory.Exists(pathString);
if (!isExists)
System.IO.Directory.CreateDirectory(pathString);
var path = string.Format("{0}\\{1}", pathString, file.FileName);
file.SaveAs(path);
}
}
}
catch(Exception ex)
{
isSavedSuccessfully = false;
}
if (isSavedSuccessfully)
{
return Json(new { Message = fName });
}
else
{
return Json(new { Message = "Error in saving file" });
}
}
Now add the following script to your view page at the and in script tag.
//File Upload response from the server
Dropzone.options.dropzoneForm = {
init: function () {
this.on("complete", function (data) {
//var res = eval('(' + data.xhr.responseText + ')');
var res = JSON.parse(data.xhr.responseText);
});
}
};
Here you can see the response from server.

formData.append() not working - checked in Chrome,Mozilla, IE

Am using Jquery FormData for the first time, but seems am missing something. In the JS - postAjax method, when new FormData() is called, it just skips the remaining lines and goes to the end of the function without any errors. What am I doing wrong here?
template.js //script files in this order
<script src="js/jquery-2.1.0.js"></script>
<script src="js/jquery.form.js"></script>
<script src="js/bootstrap.js"></script>
<script src="js/bootstrapValidator.js"></script>
<script src="js/hemoncCBCFunctions.js"></script>
<script src="js/validations.js"></script>
JSP
<form name ="newSectionSubmitForm" id="newSectionSubmitForm" class="form-horizontal" role="form" method="post" ENCTYPE="multipart/form-data">
<table>
<tr>
<td>
<input type="file" id='imageFile0' name='imageFile0' class="form-control" />
</td>
</tr>
</table>
<form>
JS
function submitNewSection(targetUrl, form) {
postAjaxData(null, 'content', targetUrl, form, null, null);
}
function postAjaxData(initiatingElement, targetElement, targetUrl, form,
additionalParamMap, successCallback) {
var $targetElement = $('#' + targetElement);
var serializedFormData;
serializedFormData = $('#' + form).serialize();
for ( var j in additionalParamMap) {
serializedFormData += "&" + j + "=" + additionalParamMap[j];
}
alert('serialized form data ' + serializedFormData);
var formData = new FormData(serializedFormData);//**exits the function no errors**
formData.append("file", $('#imageFile0').files[0]);
alert('serialized form data ' + formData);
$.ajax({
type : "POST",
cache : false,
data : formData,
url : targetUrl,
success : function(data) {
processRedirect(data);
$targetElement.html(data);
$targetElement.show();
if (successCallback != null) {
successCallback(data);
}
},
error : function(xhr, httpRequest, textStatus, errorThrown) {
var errorId = xhr.getResponseHeader("errorId");
var errorMsg = xhr.getResponseHeader("errorMessage");
if (errorId != null && errorId != undefined) {
$("#page_error").html(
"An unexpected error has occurred. Error Id: "
+ errorId);
} else {
$("#page_error").html("An unexpected error has occurred.");
}
},
});
Controller File (however the code does not reach here)
#RequestMapping(value = "/submitNewSection.html")
public String submitNewSection( MultipartHttpServletRequest req, HttpServletRequest request, Model model) {
Iterator<String> itr = req.getFileNames();
MultipartFile mpf = req.getFile(itr.next());
System.out.println("file name " + mpf.getOriginalFilename() +" uploaded!");
}
Thanks so much.

nodejs express and file uploading

Ok so ive already tried using connect-form and I couldnt get it working for some reason, but I figure I should understand how this works semi from scratch regardless.
I dont understand where the multipart/formdata file which I am uploaded is going, or how I can access it in my app when its posted to the url. -- Id like to access the file data directy, and write the file output using the node fs module. -- For instance:
app.post('/testy', function(req, res){
console.log(req.body);
console.log(req.headers);
res.redirect('back');
});
app.get('/testy', function(req, res){
res.send('<form method="post" action="/testy" enctype="multipart/form-data">'
+ '<p>Image: <input type="file" name="test" /></p>'
+ '<p><input type="submit" value="Upload" /></p>'
+ '</form>');
});
So the only req var that is actually being logged there is the req headers, body is empty. (probably supposed to be I understand that). But what I dont get is where is the file data? Looking for the php equiv of the $_FILES array I supposed. -- Here is my headers logged.
'accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'accept-language': 'en-us,en;q=0.5',
'accept-encoding': 'gzip,deflate',
'accept-charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.7',
'keep-alive': '115',
connection: 'keep-alive',
referer: 'http://127.0.0.1:3000/testy',
cookie: 'connect.sid=lDRpluTxjUJeuTmkXlybrYeZ.JYTB155s2DGce2dsyfv1Op5ISCY8uqyqJZK8NjlZ5jM; socketio=flashsocket',
'x-insight': 'activate',
'content-type': 'multipart/form-data; boundary=---------------------------5856401949371863571646035001',
'content-length': '30128' }
Any light shed upon what Im missing as always much appreciated!
Here is very verbose version without connect-form. As you can see, this is not efficient but trying to be instructive about how it works.
var express = require('express'),
fs = require('fs');
app = express.createServer();
app.post('/testy', function(req, res){
var body = '';
var header = '';
var content_type = req.headers['content-type'];
var boundary = content_type.split('; ')[1].split('=')[1];
var content_length = parseInt(req.headers['content-length']);
var headerFlag = true;
var filename = 'dummy.bin';
var filenameRegexp = /filename="(.*)"/m;
console.log('content-type: ' + content_type);
console.log('boundary: ' + boundary);
console.log('content-length: ' + content_length);
req.on('data', function(raw) {
console.log('received data length: ' + raw.length);
var i = 0;
while (i < raw.length)
if (headerFlag) {
var chars = raw.slice(i, i+4).toString();
if (chars === '\r\n\r\n') {
headerFlag = false;
header = raw.slice(0, i+4).toString();
console.log('header length: ' + header.length);
console.log('header: ');
console.log(header);
i = i + 4;
// get the filename
var result = filenameRegexp.exec(header);
if (result[1]) {
filename = result[1];
}
console.log('filename: ' + filename);
console.log('header done');
}
else {
i += 1;
}
}
else {
// parsing body including footer
body += raw.toString('binary', i, raw.length);
i = raw.length;
console.log('actual file size: ' + body.length);
}
});
req.on('end', function() {
// removing footer '\r\n'--boundary--\r\n' = (boundary.length + 8)
body = body.slice(0, body.length - (boundary.length + 8))
console.log('final file size: ' + body.length);
fs.writeFileSync('files/' + filename, body, 'binary');
console.log('done');
res.redirect('back');
})
});
app.get('/testy', function(req, res){
res.send('<form method="post" action="/testy" enctype="multipart/form-data">'
+ '<p>Image: <input type="file" name="test" /></p>'
+ '<p><input type="submit" value="Upload" /></p>'
+ '</form>');
});
app.listen(4000);
How about running this snippet from the example library?
https://github.com/visionmedia/express/blob/master/examples/multipart/app.js
/**
* Module dependencies.
*/
var express = require('express')
, form = require('connect-form');
var app = express.createServer(
// connect-form (http://github.com/visionmedia/connect-form)
// middleware uses the formidable middleware to parse urlencoded
// and multipart form data
form({ keepExtensions: true })
);
app.get('/', function(req, res){
res.send('<form method="post" enctype="multipart/form-data">'
+ '<p>Image: <input type="file" name="image" /></p>'
+ '<p><input type="submit" value="Upload" /></p>'
+ '</form>');
});
app.post('/', function(req, res, next){
// connect-form adds the req.form object
// we can (optionally) define onComplete, passing
// the exception (if any) fields parsed, and files parsed
req.form.complete(function(err, fields, files){
if (err) {
next(err);
} else {
console.log('\nuploaded %s to %s'
, files.image.filename
, files.image.path);
res.redirect('back');
}
});
// We can add listeners for several form
// events such as "progress"
req.form.on('progress', function(bytesReceived, bytesExpected){
var percent = (bytesReceived / bytesExpected * 100) | 0;
process.stdout.write('Uploading: %' + percent + '\r');
});
});
app.listen(3000);
console.log('Express app started on port 3000');
npm install express
npm install connect-form
node app.js
works fine for me...
I was able to get the connect-form package working finally, rookie mistake but, if you are using express make sure you tell the app to use the form module within your config function app.configure(function(){
app.use(form({ keepExtensions: true }));
(the in the post it will be in the files.yourfileuploadfieldname.filename variable)
-- with that said Im still interested to know how to do it from scratch, without connect-form, if its not incredibly difficult to explain.