Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/perl/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 将带有二进制映像的表单数据上载到sql server_Javascript_Asp.net_Angularjs_Jquery Ui_Asp.net Web Api - Fatal编程技术网

Javascript 将带有二进制映像的表单数据上载到sql server

Javascript 将带有二进制映像的表单数据上载到sql server,javascript,asp.net,angularjs,jquery-ui,asp.net-web-api,Javascript,Asp.net,Angularjs,Jquery Ui,Asp.net Web Api,我的目标是让用户能够上传带有一些数据字段的图像。到目前为止,我只能让其中一个工作。下面的代码使我能够将图像作为二进制文件上载到sql数据库。我需要帮助上传的数据字段和图像在相同的形式。 提前谢谢 看法 在javascript中为文件上传插件设置附加表单数据的选项。如本文所述,似乎有几种方法可以做到这一点 有些代码不是JavaScript.ok,那我该怎么办?我需要换标签吗?是的,我想我已经换了。把它改正了。谢谢你为什么不单独问这些问题?回答由多个部分组成的问题比较困难,尤其是使用不同的技术。可能

我的目标是让用户能够上传带有一些数据字段的图像。到目前为止,我只能让其中一个工作。下面的代码使我能够将图像作为二进制文件上载到sql数据库。我需要帮助上传的数据字段和图像在相同的形式。 提前谢谢

看法


在javascript中为文件上传插件设置附加表单数据的选项。如本文所述,似乎有几种方法可以做到这一点


有些代码不是JavaScript.ok,那我该怎么办?我需要换标签吗?是的,我想我已经换了。把它改正了。谢谢你为什么不单独问这些问题?回答由多个部分组成的问题比较困难,尤其是使用不同的技术。可能分为:如何上传图像和表单数据&然后:用角度显示图像和数据。他们更有可能单独回答。更正了,谢谢提示。
<form ng-submit="submitItem()" enctype='multipart/form-data'>

<input class="form-control" type="text" ng-model="itemName" placeholder="Name" />
<input class="form-control" type="text" ng-model="itemCategory" placeholder="Category" /><br />
<input class="form-control" type="text" ng-model="itemDescription" placeholder="Description..." />
<input id="fileupload" class="form-control" type="file" ng-model="imageUrl" placeholder="Image" />
<input class="form-control" type="number" ng-model="itemPrice" placeholder="Price" /><br />
<input class="btn btn-danger" type="submit" value="Add Item" />
 public class apiItemsController : ApiController
{
    ItemInterface _adapter;
    public apiItemsController()
    {
        _adapter = new ItemDataAdapter();
    }

    public apiItemsController(ItemInterface adapter)
    {
        _adapter = adapter;
    }

    //// GET api/<controller>
    public IHttpActionResult Get()

    {
     var items = _adapter.GetItems();
        return Ok(items);
    }

    // GET api/<controller>/5
    public IHttpActionResult Get(int id)
    {
        Item item = new Item();
        item = _adapter.GetItem(id);
        if (item == null)
        {
            return NotFound();
        }
        return Ok(item);
    }

  //POST
  public async Task<object> PostFile()
    {
        if (!Request.Content.IsMimeMultipartContent())
            throw new Exception();

        var provider = new MultipartMemoryStreamProvider();
        var result = new { files = new List<object>() };
        var item = new Item();
        await Request.Content.ReadAsMultipartAsync(provider)
        .ContinueWith(async (a) =>
        {
            foreach (var file in provider.Contents)
            {
                var filename = file.Headers.ContentDisposition.FileName.Trim('\"');
                var contentType = file.Headers.ContentType.ToString();
                //var requestId = int.Parse(file.Headers.ContentDisposition.Name.Trim('\"'));
                await file.ReadAsByteArrayAsync().ContinueWith(b =>
                {

                    item.Image = b.Result;
                });
            }
        }).Unwrap();
        new ItemDataAdapter().PostNewItem(item);
        return result;

    }
app.controller('MainCtrl', function ($scope, $location, $anchorScroll, $modal, $ekathuwa, $q, Item, Message, $http) {
$scope.itemArray = null;
$http.get("api/apiItems").success(function (data) {
    $scope.itemArray = data;
});
var url = "api/apiItems/File",
uploadButton = $('<button/>')
.addClass('btn btn-primary')
.prop('disabled', true)
.text('Processing...')
.on('click', function () {
  var $this = $(this),
  data = $this.data();
  $this.off('click').text('Abort').on('click', function () {
      $this.remove();
      data.abort();
  });
  data.submit().always(function () {
      $this.remove();
   });
 });
  $('#fileupload').fileupload({
    url: url,
    dataType: 'json',
    autoUpload: true,
    //acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i,
    maxFileSize: 5000000, // 5 MB
    disableImageResize: /Android(?!.*Chrome)|Opera/
    .test(window.navigator.userAgent),
    previewMaxWidth: 100,
    previewMaxHeight: 100,
    previewCrop: true
  }).on('fileuploadadd', function (e, data) {
    data.context = $('<div/>').appendTo('#files');
    $.each(data.files, function (index, file) {
        var node = $('<p/>')
        .append($('<span/>').text(file.name));
        if (!index) {
            node
            .append('<br>')
            .append(uploadButton.clone(true).data(data));
        }
        node.appendTo(data.context);
    });
  }).on('fileuploadprocessalways', function (e, data) {
    var index = data.index,
    file = data.files[index],
    node = $(data.context.children()[index]);
    if (file.preview) {
        node.prepend('<br>').prepend(file.preview);
    }
    if (file.error) {
        node.append('<br>').append($('<span class="text-danger"/>').text(file.error));
    }
    if (index + 1 === data.files.length) {
        data.context.find('button').text('Upload').prop('disabled', !!data.files.error);
    }
  }).on('fileuploadprogressall', function (e, data) {
    var progress = parseInt(data.loaded / data.total * 100, 10);
     $('#progress .progress-bar').css('width', progress + '%');
  }).on('fileuploaddone', function (e, data) {
    $.each(data.result.files, function (index, file) {
        if (file.url) {
            var link = $('<a>').attr('target', '_blank').prop('href', file.url);
            $(data.context.children()[index]).wrap(link);
        } else if (file.error) {
            var error = $('<span class="text-danger"/>').text(file.error);
            $(data.context.children()[index]).append('<br>').append(error);
        }
    });
  }).on('fileuploadfail', function (e, data) {
    $.each(data.files, function (index, file) {
        var error = $('<span class="text-danger"/>').text('File upload failed.');
        $(data.context.children()[index]).append('<br>').append(error);
    });
  }).bind('fileuploadalways', function (e, data) {
    console.log(data);
    if (data._response.textStatus === "success") {
        for (var i = 0; i < data._response.jqXHR.responseJSON.files.length; i++) {
            //var file = data._response.jqXHR.responseJSON.files[i];
            //model().request.requestAttachments.push({ fileName:  

      ko.observable(file.name), id: ko.observable(file.id) });
        }
        $('#progress .progress-bar').css('width', '0%');
    }

  }).prop('disabled', !$.support.fileInput)
         .parent().addClass($.support.fileInput ? undefined : 'disabled');
public class ItemDataAdapter : ItemInterface
{

    public List<Item> GetItems()
    {
       ApplicationDbContext db = new ApplicationDbContext();
        List<Item> model = new List<Item>();
        model = db.Items.ToList();
        return model;
    }

    public Item GetItem(int id)
    {
        ApplicationDbContext db = new ApplicationDbContext();
        Item model = new Item();
        model = db.Items.Where(j => j.ItemId == id)

                       .FirstOrDefault();
        return model;
    }
  public List<Item> PostNewItem( Item newItem)
    {
        ApplicationDbContext db = new ApplicationDbContext();
        //Item item = new Item();
        //item.ItemDescription = newItem.ItemDescription;
        //item.ItemId = newItem.ItemId;
        //item.ItemName = newItem.ItemName;
        //item.ItemPrice = newItem.ItemPrice;
        //item.ItemCategory = newItem.ItemCategory;
        //item.Image = newItem.Image;
        db.Items.Add(newItem);
        db.SaveChanges();

        // ????
        return db.Items.ToList();
    }
public class Item
{
    public int ItemId { get; set; }
    public string ItemName { get; set; }
    public string ItemDescription { get; set; }
    public int ItemPrice { get; set; }
    public byte[] Image { get; set; }
    public string ItemCategory { get; set; }
    public bool Hidden { get; set; }
}
$('#fileupload').fileupload({
    formData: {example: 'test'},
    url: url,
    dataType: 'json',
    autoUpload: true,
    //acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i,
    maxFileSize: 5000000, // 5 MB
    disableImageResize: /Android(?!.*Chrome)|Opera/
    .test(window.navigator.userAgent),
    previewMaxWidth: 100,
    previewMaxHeight: 100,
    previewCrop: true
  })