我使用ASP.NET MVC 5创建了一个网站,这个网站也可以作为Web应用程序在移动设备上使用。但是现在我想在用户使用移动设备上的应用程序时添加使用手机摄像头扫描条形码的功能。当然,有像PhoneGap这样的工具可以读取条形码,但关键是我想在我的ASP.NET MVC 5项目中添加此功能。
那么,在ASP.NET MVC 5中是否有一种通过移动摄像头读取条形码的方法?
我使用ASP.NET MVC 5创建了一个网站,这个网站也可以作为Web应用程序在移动设备上使用。但是现在我想在用户使用移动设备上的应用程序时添加使用手机摄像头扫描条形码的功能。当然,有像PhoneGap这样的工具可以读取条形码,但关键是我想在我的ASP.NET MVC 5项目中添加此功能。
那么,在ASP.NET MVC 5中是否有一种通过移动摄像头读取条形码的方法?
<form>
<input type="file" class="upload" size="45" name="file" id="file">
</form>
将 <input type="file"...>
放在 form
标签中非常重要。
接下来使用 JavaScript。我使用它是因为我希望在单击浏览按钮时立即调用控制器。您也可以使用提交按钮。
JavaScript:
$('#file').on("change", function () {
for (i = 0; i < $('form').length; i++) {
if ($('form').get(i)[0].value != "") /* get the file tag, you have to customize this code */
{
var formdata = new FormData($('form').get(i));
CallService(formdata);
break;
}
}
});
function CallService(file) {
$.ajax({
url: '@Url.Action("Scan", "Home")',
type: 'POST',
data: file,
cache: false,
processData: false,
contentType: false,
success: function (barcode) {
alert(barcode);
},
error: function () {
alert("ERROR");
}
});
}
public JsonResult Scan(HttpPostedFileBase file)
{
string barcode = "";
try
{
string path = "";
if (file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
path = Path.Combine(Server.MapPath("~/App_Data"), fileName);
file.SaveAs(path);
}
// Now we try to read the barcode
// Instantiate BarCodeReader object
BarCodeReader reader = new BarCodeReader(path, BarCodeReadType.Code39Standard);
System.Drawing.Image img = System.Drawing.Image.FromFile(path);
System.Diagnostics.Debug.WriteLine("Width:" + img.Width + " - Height:" + img.Height);
try
{
// read Code39 bar code
while (reader.Read())
{
// detect bar code orientation
ViewBag.Title = reader.GetCodeText();
barcode = reader.GetCodeText();
}
reader.Close();
}
catch (Exception exp)
{
System.Console.Write(exp.Message);
}
}
catch (Exception ex)
{
ViewBag.Title = ex.Message;
}
return Json(barcode);
}
}
我已经编辑了代码,以使用Aspose.BarCode包;
public JsonResult ScanDelivered(HttpPostedFileBase file)
{
string readedBarcode = "";
try
{
string path = "";
if (file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
path = Path.Combine(Server.MapPath("~/App_Data"), fileName);
file.SaveAs(path);
}
System.Drawing.Image img = System.Drawing.Image.FromFile(path);
System.Diagnostics.Debug.WriteLine("Width:" + img.Width + " - Height:" + img.Height);
try
{
// Initialize barcode reader
using (BarCodeReader reader = new BarCodeReader(path, DecodeType.AllSupportedTypes))
{
// Recognize barcodes on the image
foreach (var barcode in reader.ReadBarCodes())
{
readedBarcode = barcode.CodeText;
}
}
}
catch (Exception exp)
{
System.Console.Write(exp.Message);
}
}
catch (Exception ex)
{
ViewBag.Title = ex.Message;
}
return Json(readedBarcode);
}