Cod*_*ope 6 mobile camera barcode asp.net-mvc-5
我使用 ASP.NET MVC 5 创建了一个网站。该网站也可以作为 Web 应用程序在移动设备上使用。但现在我想添加用户在手机上使用该应用程序时使用移动相机扫描条形码的可能性。当然,有像phonegap这样的工具可以读取条形码,但重点是我想在我的ASP.NET MVC 5项目中添加此功能。
那么有没有办法在 ASP.NET MVC 5 中通过手机摄像头读取条形码呢?
我已经解决了这个问题,这是解决方案:在视图(Index.chtml)中:
<form>
<input type="file" class="upload" size="45" name="file" id="file">
</form>
Run Code Online (Sandbox Code Playgroud)
<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");
}
});
}
Run Code Online (Sandbox Code Playgroud)
接下来我们分析服务器中的图像并读取它的条形码。我正在使用 Aspose.BarCode 库:
HomeController.cs
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);
}
}
Run Code Online (Sandbox Code Playgroud)
现在,解码后的条形码返回到视图中。
归档时间: |
|
查看次数: |
18982 次 |
最近记录: |