提问者:小点点

如何让用户在web应用程序中一次上传一定数量的图片?


我有一个网络应用写在节点,我希望用户能够提交他的图像,如果他们采取了一个设定的数量的图片使用他们的手机,例如20张图片(他们不能提交更多或更少)。我知道我可以收集一个html图像使用下面的行,但不太知道如何执行唯一上传如果用户已采取x图片规则。

<input type="file" accept="image/*" capture="user">

共3个答案

匿名用户

您只需从input.files.length中获取输入中选择的文件数。

这个代码段应该可以帮助您。我在代码中插入了注释来澄清它,注释也包含了您应该使用的代码,以获得更好的体验。

如果您不是ES6用户,请查看下面的代码片段。另外,请查看本答案底部的进一步阅读部分。

null

const theInput = document.getElementById('theInput');
const theChooser = document.getElementById('theChooser');

let theNumber; //Or "let theNumber = your-default-number" if you want to avoid possible error when user selected 0 files

theChooser.oninput = () => {
  theNumber = theChooser.value * 1 //Multiplying it to 1 will make the (already number) input a number anyways
}

theInput.onchange = () => {
  theInput.files.length === theNumber ? theFunction() : theWarning()
  // To do nothing when user selected 0 files (user clicked Cancel) do this
  /*
  theInput.files.length === theNumber ? theFunction() : theInput.files.length === 0 ? null : theWarning()
  */
}

function theFunction() {
  console.log(`You chose exactly ${theNumber} files. Yay!`);
}

function theWarning() {
  console.log(`¯\\_(ツ)_/¯ Watcha doing, you told to choose only ${theNumber} files.`);
}
<input type="number" id="theChooser" placeholder="Set your number of files">
<br>
<input type="file" id="theInput" multiple>

匿名用户

要允许多个文件上传,您必须在input标记中包含multiple属性。

<input type="file" accept="image/*" capture="user" multiple="true" id="file-inp" />

您应该验证上载到客户端的文件数量,并在错误操作的情况下警告用户。

$('#file-inp').change(function() {
    var files = $(this)[0].files;
    if(files.length != 20){
        alert("only a total of 20 files should be uploaded");
    }
    //enter code here
});

匿名用户

您可以引用sample as,您需要在HTML as中使用'multiple'关键字,

<input type="file" name="userPhoto" multiple />

IMHO,Multer是一个很好的npm包处理文件上传。您可以配置no。您希望允许上载的文件的

 var upload = multer({ storage : storage }).array('userPhoto',20);

示例Node.js代码

var bodyParser = require("body-parser");
var multer = require('multer');
var app = express();

app.use(bodyParser.json());

var storage = multer.diskStorage({
  destination: function (req, file, callback) {
    callback(null, './uploads');
  },
  filename: function (req, file, callback) {
    callback(null, file.fieldname + '-' + Date.now());
  }
});

var upload = multer({ storage : storage }).array('userPhoto',20); // here you can set file limit to upload

app.get('/',function(req,res){
      res.sendFile(__dirname + "/index.html");
});

app.post('/api/photo',function(req,res){
    upload(req,res,function(err) {
        //console.log(req.body);
        //console.log(req.files);
        if(err) {
            return res.end("Error uploading file.");
        }
        res.end("File is uploaded");
    });
});

app.listen(3000,function(){
    console.log("Working on port 3000");
});