我正试图使用自定义的 MultipartEntity
从 Android 应用程序上传图像,该实体还会更新一个 ProgressDialog
(这也是我使用已弃用的 MultipartEntity
的原因)。
相关的 Java 代码:
File file = new File(imgPath);
HttpPost post = new HttpPost("http://" + SERVER + "/upload");
MultipartEntity entity = new MyMultipartEntity(new MyMultipartEntity.ProgressListener()
{
public void transferred(long num)
{
publishProgress((int) ((num / (float) totalSize) * 100));
Log.d("DEBUG", num + " - " + totalSize);
}
});
ContentBody cbFile = new FileBody(file, "image/jpeg");
entity.addPart("source", cbFile);
totalSize = entity.getContentLength();
post.setEntity(entity);
HttpResponse response = client.execute(post);
int statusCode = response.getStatusLine().getStatusCode();
if(statusCode == HttpStatus.SC_OK){
String fullRes = EntityUtils.toString(response.getEntity());
Log.d("DEBUG", fullRes);
} else {
Log.d("DEBUG", "HTTP Fail, Response Code: " + statusCode);
}
Node.js服务器文件:
var fs = require('fs');
var express = require('express');
var app = express();
var multer = require('multer');
var upload = multer(
{
limits: {
fieldNameSize: 999999999,
fieldSize: 999999999
},
dest: 'uploads/' }
);
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', upload.any(), function(req, res){
console.log(req.files);
var tmp_path = req.files[0].path;
var target_path = 'uploads/' + req.files[0].originalname;
var src = fs.createReadStream(tmp_path);
var dest = fs.createWriteStream(target_path);
src.pipe(dest);
src.on('end', function() { res.send("ok"); });
src.on('error', function(err) { res.send({error: "upload failed"}); });
});
app.get('/info', function(req, res){
console.log(__dirname);
res.send("image upload server: post /upload");
});
app.listen(8080);
console.log('started server on localhost...');
我也尝试使用
upload.single()
方法(通过表单工作),但需要字段名称,我不确定如何/是否能将其添加到Java多部分实体对象中。目前收到的请求是一个空的 files
数组和一个包含图像原始数据的请求体上的 source
变量,因此基本上看起来像 multer 根本没有执行任何操作。我错过了什么吗?谢谢!