将图像作为字节数组上载到文件夹中的服务器

时间:2017-05-09 09:39:21

标签: c# xamarin

我的问题是如何将字节数组上传到服务器?

我已经将它转换为字节数组,如下所示:

Stream stream = ContentResolver.OpenInputStream(data.Data);
Bitmap bitmap = BitmapFactory.DecodeStream(stream);
MemoryStream memStream = new MemoryStream();
bitmap.Compress(Bitmap.CompressFormat.Jpeg, 50, memStream);                
byte[] picData;
picData = memStream.ToArray();

现在我想将picData上传到文件夹" pics"

中的服务器

2 个答案:

答案 0 :(得分:0)

对不起,是的,我有这样的MVC控制器:

public class DefaultController : Controller
    {
        // GET: Default
        public ActionResult FileUpload(HttpPostedFileBase file)
        {
            int i = 0;
            try
            {
                if (file != null)
                {
                    i = 1;

                    string path = Path.Combine(Server.MapPath("~/Content/pictures"), Path.GetFileName(file.FileName));
                    file.SaveAs(path);

                    string FileName = Path.GetFileName(file.FileName);
                    byte[] thePictureAsBytes = new byte[file.ContentLength];
                    using (BinaryReader theReader = new BinaryReader(file.InputStream))

                    {
                        thePictureAsBytes = theReader.ReadBytes(file.ContentLength);
                    }

                    return Json(new { id = "success" }, JsonRequestBehavior.AllowGet);
                }
            }
            catch (Exception ex)
            {
                return Json(new { id = ex.Message }, JsonRequestBehavior.AllowGet);
            }
            return Json(new { id = i }, JsonRequestBehavior.AllowGet);

        }

    }
}

答案 1 :(得分:0)

public string UploadToServer(byte[] image)
    {
        try
        {
            MemoryStream ms = new MemoryStream(image);
            var i = Bitmap.FromStream(ms);
            string time = DateTime.Now.ToString("dd_MM_yyyy_HH_mm_ss");
            string Filename = "IMG_" + time + ".png";
            string UploadPath = HttpContext.Current.Server.MapPath("~/Image");
            if (!Directory.Exists(UploadPath))
                Directory.CreateDirectory(UploadPath);
            string NewFilePath = Path.Combine(UploadPath, Filename);
            File.WriteAllBytes(NewFilePath, image);
            return Filename;
        }
        catch (Exception)
        {
            throw;
        }
    }