c # сохранить вложение изображения из входного тега cshtml в папке VS Project - PullRequest
0 голосов
/ 23 сентября 2019

У меня есть форма CSHTML в Visual Studio 2017, в которой я хочу сохранить вложения в папке «YourRightsFiles» в основной папке проекта и сохранить сведения в базе данных для блога / доски объявлений для веб-сайта, к которому относится форма,Исходя из кода, показанного в разделе «Загрузка изображения» в следующем руководстве Microsoft - https://docs.microsoft.com/en-us/aspnet/web-pages/overview/ui-layouts-and-themes/9-working-with-images - я написал следующий код для формы:

                <div id="creds" style="margin-top:50px;float:right;visibility:hidden;height:0">
                    <form method="post" enctype="multipart/form-data">
                        <span style="font-weight:bold">First Name: </span><br> <input type="text" name="first name" required><br><br>
                        <span style="font-weight:bold">Last Name: </span><br> <input type="text" name="last name" required><br><br>
                        <span style="font-weight:bold">Job Title: </span><br> <input type="text" name="job title" required><br><br>
                        <span style="font-weight:bold">Subject: </span><br> <input type="text" name="subject" cols="30" required><br><br>
                        <div id="attachments">
                        <span style="font-weight:bold">Attachments (images and videos only): </span><br> <input type="file" accept="video/*, image/*" name="attachment0" cols="30"><br><br>
                        <input onclick="return add_attachment()" readonly value="Add Another Attachment" style="width:auto;background-color:lightgrey;border-color:black;border-width:1px;margin-bottom:30px;padding:3px;border-radius:6px;"><br><br>
                        <script>
                            function add_attachment() {
                                var count = 0;
                                var input_tags = document.getElementsByTagName("input");
                                for (var i = 0; i < input_tags.length; i++) {
                                    if (input_tags[i].name.search("attachment") != null) {
                                        count = count + 1;
                                    }
                                }
                                var attach_html = "<input type=\"file\" accept=\"video/*, image/*\" name=\"attachment" + count.toString() + "\" cols=\"30\"><br><br>";
                                document.getElementById("attachments").innerHTML = document.getElementById("attachments").innerHTML + attach_html;
                            }
                        </script>
                        </div>
                        <span style="font-weight:bold">Message: </span><br> <textarea type="text" name="message" rows="4" cols="30" required></textarea><br><br>

                        <input type="submit" name="Submit" readonly value="Submit Message" style="width:auto;background-color:lightgrey;border-color:black;border-width:1px;margin-bottom:30px;padding:3px;border-radius:6px;">
                    </form>
                </div>
                @if (IsPost)
                {
                    var connectionString = "MY CONNECTION STRING";
                    var providerName = "System.Data.SqlClient";
                    var db = Database.OpenConnectionString(connectionString, providerName);

                    if (Request.Form["Submit"] == "Submit Message")
                    {
                        var firstName = Request.Form["first name"];
                        var lastName = Request.Form["last name"];
                        var jobTitle = Request.Form["job title"];
                        var subject = Request.Form["subject"];
                        var message = Request.Form["message"];
                        var all_fields = Request.Form.AllKeys;
                        System.Diagnostics.Debug.Write(all_fields);
                        var insertQuery = "insert into YourRights values(@0,@1,@2,@3,@4)";
                        foreach(var field in all_fields) {
                            if (field.ToString().Contains("attachment")) {
                                WebImage photo = WebImage.GetImageFromRequest(field.ToString());
                                var newFileName = "";
                                var imagePath = "";
                                if (photo != null)
                                {
                                    newFileName = Guid.NewGuid().ToString() + "_" +
                                        Path.GetFileName(photo.FileName);
                                    imagePath = @"YourRightsFiles\" + newFileName;

                                    photo.Save(@"~\" + imagePath);
                                }
                            }
                        }

                        db.Execute(insertQuery, firstName, lastName, subject, message, jobTitle);
                    }
                    db.Close();
                }

Код, похоже, несохраните файл в «YourRightsFiles».Я также попытался просто сохранить в основной папке проекта:

imagePath = @"\" + newFileName;

Но это тоже не сработало.Весь код, связанный с вставкой базы данных, работает, поэтому нет проблем с отправкой формы, и я не получаю никаких ошибок во время демонстрации, даже в консоли.Я не уверен, что я делаю не так здесь

...