I recently saw a tutorial to upload some photos from here [https://aguacatelang.wordpress.com/2012/08/19/android-multipart-upload-to-node-js/][1]
我最近看到了一个从这里上传一些照片的教程[https://aguacatelang.wordpress.com/2012/08/19/android-multipart-upload-to-node-js/] [1]
I've just learned nodejs and less understanding of the structure of programming languages, I found a mistake like this :
我刚刚学习了nodejs并且对编程语言的结构了解不足,我发现了这样的错误:
home/je/Documents/BE/UploadFoto/app.js:12
var db = new Db('photos', new dbServer('localhost', dbConnection.'27017', {}))
^^^^^^^
SyntaxError: Unexpected string
at Module._compile (module.js:439:25)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:935:3
this is original source code :
这是原始源代码:
var express = require('express');
var app = express()
var fs = require('fs');
var im = require('imagemagick');
var Db = require('mongodb').Db;
var dbServer = require('mongodb').Server;
var dbConnection = require('mongodb').Connection;
var db = new Db('photos', new dbServer('localhost', dbConnection.'DEFAULT_PORT', {}));
db.open(function(err, db){});
app.use(express.bodyParser())
app.get('/', function(req, res){
res.send(
'<form action="/upload" method="post" enctype="multipart/form-data">'+
'<input type="file" name="source">'+
'<input type="submit" value="Upload">'+
'</form>'
);
});
app.post('/upload', function(req, res){
console.log("Received file:\n" + JSON.stringify(req.files));
var photoDir = __dirname+"/photos/";
var thumbnailsDir = __dirname+"/photos/thumbnails/";
var photoName = req.files.source.name;
fs.rename(
req.files.source.path,
photoDir+photoName,
function(err){
if(err != null){
console.log(err)
res.send({error:"Server Writting No Good"});
} else {
im.resize(
{
srcData:fs.readFileSync(photoDir+photoName, 'binary'),
width:256
},
function(err, stdout, stderr){
if(err != null){
console.log('stdout : '+stdout)
res.send({error:"Resizeing No Good"});
} else {
//console.log('ELSE stdout : '+stdout)
fs.writeFileSync(thumbnailsDir+"thumb_"+photoName, stdout, 'binary');
res.send("Ok");
}
}
);
}
}
);
});
app.get('/info', function(req, res){
console.log(__dirname);
res.send("ok");
});
app.listen(8000);
console.log('connected to localhost....')
I switched DEFAULT_PORT to 27017 because in my PC the port that is used mongodb:localhost/27017. May someone help me? thanks
我将DEFAULT_PORT切换为27017,因为在我的PC中使用了mongodb的端口:localhost / 27017。愿有人帮帮我吗?谢谢
2 个解决方案
#1
BodyParser no longer supports parsing multypart requests. You should try using one of these modules.
BodyParser不再支持解析多部分请求。您应该尝试使用其中一个模块。
Here is a simple example using multiparty:
这是一个使用multiparty的简单示例:
var multipart = require('multiparty');
app.post('/upload', function(req, res){
var form = new multipart.Form();
form.parse(req, function(err, fields, files) {
console.log(files);//list all files uploaded
//put in here all the logic applied to your files.
});
return;
});
Or you can use it as a middleware, like this:
或者您可以将其用作中间件,如下所示:
var multipart = require('connect-multiparty');
app.use(multipart());
app.post('/upload', function(req, res) {
console.log(req.files);//list all files uploaded
// apply all logic here
});
#2
I am sending files like Audios,Images and videos etc from Android Using Retrofit ,At server side i am using node.js .
我正在使用Retrofit从Android发送音频,图像和视频等文件,在服务器端我使用node.js。
on btnUpload click i am uploading my files to server .
在btnUpload上点击我将我的文件上传到服务器。
btnUpload.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(MusicActivity.this, ""+ commonAdapter.getSelectedItems().size(), Toast.LENGTH_SHORT).show();
String fileUri=null;
File file=null;
RequestBody requestFile=null;
MultipartBody.Part part=null;
ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);
for(int i=0;i<commonAdapter.getSelectedItems().size();i++)
{
fileUri = commonAdapter.getSelectedItems().get(i);
file = new File(fileUri);
requestFile = RequestBody.create(MediaType.parse(fileUri), file);
//music name must be same as music at node.js ,
//if its different then it will not worked.
part = MultipartBody.Part.createFormData("music", file.getName(), requestFile);
Call<UploadObject> myResponseCall = apiService.uploadMusic(part);
myResponseCall.enqueue(new Callback<UploadObject>() {
@Override
public void onResponse(Call<UploadObject> call, Response<UploadObject> response) {
Log.d("kkkk","ok response");
}
@Override
public void onFailure(Call<UploadObject> call, Throwable t) {
// Toast.makeText(ImagesActivity.this, "Error Occured ! ", Toast.LENGTH_LONG).show();
Log.d("kkkk","on failed");
}
});
}
}
});
My ApiInterface for Retrofit
我的ApiInterface for Retrofit
public interface ApiInterface {
@Multipart
@POST("api/uploadImage")
Call<UploadObject> uploadImage(@Part MultipartBody.Part file);
@Multipart
@POST("api/uploadVideo")
Call<UploadObject> uploadVideo(@Part MultipartBody.Part file);
@Multipart
@POST("api/uploadMusic")
Call<UploadObject> uploadMusic(@Part MultipartBody.Part file);
}
Its my getSelectedItem :- which return selected Items
它是我的getSelectedItem: - 返回所选的项目
public ArrayList<String> getSelectedItems()
{
return selectedItems;
}
At Node.js I am using multer
在Node.js我正在使用multer
var express = require('express')
//const bodyParser = require('body-parser');
var multer = require('multer')
var upload = multer({ dest: 'uploads/' })
var fs = require('fs');
var app = express()
// app.use(bodyParser.json());
// app.use(bodyParser.urlencoded({ extended: true }));
app.post('/api/uploadImage', upload.single('image'), function (req, res, next) {
var tmp_path = req.file.path;
var target_path = 'uploads/' + req.file.originalname;
/** A better way to copy the uploaded file. **/
var src = fs.createReadStream(tmp_path);
var dest = fs.createWriteStream(target_path);
src.pipe(dest);
src.on('end', function() { console.log('complete') });
src.on('error', function(err) { console.log('error'); });
fs.unlink(tmp_path);
});
app.post('/api/uploadVideo', upload.single('video'), function (req, res, next) {
var tmp_path = req.file.path;
var target_path = 'uploads/' + req.file.originalname;
/** A better way to copy the uploaded file. **/
var src = fs.createReadStream(tmp_path);
var dest = fs.createWriteStream(target_path);
src.pipe(dest);
src.on('end', function() { console.log('complete') });
src.on('error', function(err) { console.log('error'); });
fs.unlink(tmp_path);
});
app.post('/api/uploadMusic', upload.single('music'), function (req, res, next) {
var tmp_path = req.file.path;
var target_path = 'uploads/' + req.file.originalname;
/** A better way to copy the uploaded file. **/
var src = fs.createReadStream(tmp_path);
var dest = fs.createWriteStream(target_path);
src.pipe(dest);
src.on('end', function() { console.log('complete') });
src.on('error', function(err) { console.log('error'); });
fs.unlink(tmp_path);
});
app.listen(8080,(res,err)=>{
if(err)
console.log('error occured while connecting port');
else
console.log('Server is Up');
});
I hope its help You!
希望对你有所帮助!
#1
BodyParser no longer supports parsing multypart requests. You should try using one of these modules.
BodyParser不再支持解析多部分请求。您应该尝试使用其中一个模块。
Here is a simple example using multiparty:
这是一个使用multiparty的简单示例:
var multipart = require('multiparty');
app.post('/upload', function(req, res){
var form = new multipart.Form();
form.parse(req, function(err, fields, files) {
console.log(files);//list all files uploaded
//put in here all the logic applied to your files.
});
return;
});
Or you can use it as a middleware, like this:
或者您可以将其用作中间件,如下所示:
var multipart = require('connect-multiparty');
app.use(multipart());
app.post('/upload', function(req, res) {
console.log(req.files);//list all files uploaded
// apply all logic here
});
#2
I am sending files like Audios,Images and videos etc from Android Using Retrofit ,At server side i am using node.js .
我正在使用Retrofit从Android发送音频,图像和视频等文件,在服务器端我使用node.js。
on btnUpload click i am uploading my files to server .
在btnUpload上点击我将我的文件上传到服务器。
btnUpload.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(MusicActivity.this, ""+ commonAdapter.getSelectedItems().size(), Toast.LENGTH_SHORT).show();
String fileUri=null;
File file=null;
RequestBody requestFile=null;
MultipartBody.Part part=null;
ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);
for(int i=0;i<commonAdapter.getSelectedItems().size();i++)
{
fileUri = commonAdapter.getSelectedItems().get(i);
file = new File(fileUri);
requestFile = RequestBody.create(MediaType.parse(fileUri), file);
//music name must be same as music at node.js ,
//if its different then it will not worked.
part = MultipartBody.Part.createFormData("music", file.getName(), requestFile);
Call<UploadObject> myResponseCall = apiService.uploadMusic(part);
myResponseCall.enqueue(new Callback<UploadObject>() {
@Override
public void onResponse(Call<UploadObject> call, Response<UploadObject> response) {
Log.d("kkkk","ok response");
}
@Override
public void onFailure(Call<UploadObject> call, Throwable t) {
// Toast.makeText(ImagesActivity.this, "Error Occured ! ", Toast.LENGTH_LONG).show();
Log.d("kkkk","on failed");
}
});
}
}
});
My ApiInterface for Retrofit
我的ApiInterface for Retrofit
public interface ApiInterface {
@Multipart
@POST("api/uploadImage")
Call<UploadObject> uploadImage(@Part MultipartBody.Part file);
@Multipart
@POST("api/uploadVideo")
Call<UploadObject> uploadVideo(@Part MultipartBody.Part file);
@Multipart
@POST("api/uploadMusic")
Call<UploadObject> uploadMusic(@Part MultipartBody.Part file);
}
Its my getSelectedItem :- which return selected Items
它是我的getSelectedItem: - 返回所选的项目
public ArrayList<String> getSelectedItems()
{
return selectedItems;
}
At Node.js I am using multer
在Node.js我正在使用multer
var express = require('express')
//const bodyParser = require('body-parser');
var multer = require('multer')
var upload = multer({ dest: 'uploads/' })
var fs = require('fs');
var app = express()
// app.use(bodyParser.json());
// app.use(bodyParser.urlencoded({ extended: true }));
app.post('/api/uploadImage', upload.single('image'), function (req, res, next) {
var tmp_path = req.file.path;
var target_path = 'uploads/' + req.file.originalname;
/** A better way to copy the uploaded file. **/
var src = fs.createReadStream(tmp_path);
var dest = fs.createWriteStream(target_path);
src.pipe(dest);
src.on('end', function() { console.log('complete') });
src.on('error', function(err) { console.log('error'); });
fs.unlink(tmp_path);
});
app.post('/api/uploadVideo', upload.single('video'), function (req, res, next) {
var tmp_path = req.file.path;
var target_path = 'uploads/' + req.file.originalname;
/** A better way to copy the uploaded file. **/
var src = fs.createReadStream(tmp_path);
var dest = fs.createWriteStream(target_path);
src.pipe(dest);
src.on('end', function() { console.log('complete') });
src.on('error', function(err) { console.log('error'); });
fs.unlink(tmp_path);
});
app.post('/api/uploadMusic', upload.single('music'), function (req, res, next) {
var tmp_path = req.file.path;
var target_path = 'uploads/' + req.file.originalname;
/** A better way to copy the uploaded file. **/
var src = fs.createReadStream(tmp_path);
var dest = fs.createWriteStream(target_path);
src.pipe(dest);
src.on('end', function() { console.log('complete') });
src.on('error', function(err) { console.log('error'); });
fs.unlink(tmp_path);
});
app.listen(8080,(res,err)=>{
if(err)
console.log('error occured while connecting port');
else
console.log('Server is Up');
});
I hope its help You!
希望对你有所帮助!