반응형

0. 사전에 준비해야 할것

0-1. 사용하고자하는 이메일에서 smtp가 가능한지 확인

0-2. 만약 가능하다면 smtp의 주소와 포트 번호를 확인한다.

 

1. NuGet 에서 MimeKit 을 다운로드 받습니다.

2. MailSender.cs 를 원하는 폴더에 구현합니다.

using MimeKit;
using System;
using System.IO;
using System.Text; 

namespace Project.Common
{
    public class MailSender
    {
    	// toMail: 보내고자하는 이메일주소
        // title: 보내고자하는 이메일의 제목
        // mailContent : 보내고자하는 이메일의 내용(HTML 태그형식의 string 값)
        public void Send(string toMail, string title, string mailContent ) {
            if (toMail.IndexOf("@") > -1)
            {
                string id = (toMail.Split('@')[0]).ToString();
                using (var client = new MailKit.Net.Smtp.SmtpClient())
                {
                	// 사용하고자하는 email의 smtps 주소, 포트를 입력합니다.
                    client.Connect("smtps.SMTPS_ADDRESS.com", SMTPS_PORT, true);
                    // 당신의 아이디와 비밀번호를 입력합니다.
                    client.Authenticate("YOUR_ID", "YOUR_PASSWORD");

                    var message = new MimeMessage();
					//받는사람이 보는
                    // 보내는 사람의 대표이름과 보내는 사람 이메일을 설정합니다.
                    message.From.Add(new MailboxAddress("EMAIL_TITLE", "EMAIL_FROM"));
                    message.To.Add(new MailboxAddress(id, toMail));

                    message.Subject = title;

                    var builder = new BodyBuilder();

                    builder.HtmlBody = mailContent;                    

                    message.Body = builder.ToMessageBody();
                    client.Send(message);
                    client.Disconnect(true);

                }
            }
        }
    }
}

어디서든지 Send를 통해 보내면됩니다.

반응형
반응형

.cshtml (razor page)

@using (Html.BeginForm("FileUpload", "Home", FormMethod.Post, 
                            new { enctype = "multipart/form-data" }))
{  
    <label for="file">Upload Image:</label> 
    <input type="file" name="file" id="file" style="width: 100%;" /> 
    <input type="submit" value="Upload" class="submit" /> 
}

Controller

(HomeController.cs)

public ActionResult FileUpload(HttpPostedFileBase file)
    {
        if (file != null)
        {
            try
    {
        HttpFileCollection hfc = HttpContext.Current.Request.Files;
        string path = "/content/files/contact/";

        for (int i = 0; i < hfc.Count; i++)
        {
            HttpPostedFile hpf = hfc[i];
            if (hpf.ContentLength > 0)
            {
                string fileName = "";
                if (Request.Browser.Browser == "IE")
                {
                    fileName = Path.GetFileName(hpf.FileName);
                }
                else
                {
                    fileName = hpf.FileName;
                }
                string fullPathWithFileName = path + fileName;
                hpf.SaveAs(Server.MapPath(fullPathWithFileName));
            }
        }

    }
    catch (Exception ex)
    {
        throw ex;
    }

        }
        // after successfully uploading redirect the user
        return RedirectToAction("actionname", "controller name");
    }

이러면 /content/files/contact/ 의 경로에 이미지파일들이 업로드 된다.

날짜와 사용자의 index 등을 잘 조합해서 중복되지 않는 파일명을 만들어 업로드하고 

DB에 경로를 지정해주면 될것입니다.

 

출처 : https://stackoverflow.com/questions/16255882/uploading-displaying-images-in-mvc-4

반응형
반응형

Creating MVC Application

Let us implement these in a sample Application. Open Visual Studio. Go to File->New->Project. Give a suitable name to the Application. Click OK.



Select MVC Template. Click OK.



Adding Folder

We will add a folder to store the files in the application. Here, I have added a folder in the application.



Adding Controller

Let us add a controller. Right click on the Controller. Add->Controller.



Select MVC 5 Controller -Empty. Click Add.



Give a suitable name to the controller.



Write the following code in the controller.

 

using System;  
usingSystem.Collections.Generic;  
using System.IO;  
usingSystem.Linq;  
usingSystem.Web;  
usingSystem.Web.Mvc;  
namespaceFileUpload.Controllers  
{  
    public class UploadController: Controller  
    {  
        // GET: Upload  
        publicActionResult Index()  
        {  
            return View();  
        }  
        [HttpGet]  
        publicActionResultUploadFile()  
        {  
            return View();  
        }  
        [HttpPost]  
        publicActionResultUploadFile(HttpPostedFileBase file)  
        {  
            try  
            {  
                if (file.ContentLength > 0)  
                {  
                    string _FileName = Path.GetFileName(file.FileName);  
                    string _path = Path.Combine(Server.MapPath("~/UploadedFiles"), _FileName);  
                    file.SaveAs(_path);  
                }  
                ViewBag.Message = "File Uploaded Successfully!!";  
                return View();  
            }  
            catch  
            {  
                ViewBag.Message = "File upload failed!!";  
                return View();  
            }  
        }  
    }  
}  

Adding View

Right click on UploadFileActionResult. Go to Add View.



Select the empty template. Click add.



Write the following code in the View.

@{  
    ViewBag.Title = "UploadFile";  
}  
   
<h2>UploadFile</h2>  
   
@using(Html.BeginForm("UploadFile","Upload", FormMethod.Post, new { enctype="multipart/form-data"}))  
{  
      
    <div>  
        @Html.TextBox("file", "", new {  type= "file"}) <br />  
   
        <input type="submit" value="Upload" />  
   
        @ViewBag.Message  
   
    </div>  
      
      
}  

Browse the Application

Let us now run the Application and check if it is working fine or not. Browse the Application.



Click upload. I have debugged the code to verify that the file gets uploaded successfully.



The code is working as per the expectations, as it hits the success message. We should get this message on the View, as well.



We will verify the file uploaded, by opening the folder in the Application’s directory.



Summary

Hence, we have just learned how to upload the file in ASP.NET MVC. I hope this post is useful to developers.

 

출처 : https://www.c-sharpcorner.com/article/upload-files-in-asp-net-mvc-5/

반응형
반응형

There are quite a bit of answers to handle it client side, but you can change the output server side if you desired.

There are a few ways to approach this, I'll start with the basics. You'll have to subclass the JsonResult class and override the ExecuteResult method. From there you can take a few different approaches to change the serialization.

Approach 1: The default implementation uses the . If you take a look at the documentation, you can use the RegisterConverters method to add custom . There are a few problems with this though: The JavaScriptConverter serializes to a dictionary, that is it takes an object and serializes to a Json dictionary. In order to make the object serialize to a string it requires a bit of hackery, see . This particular hack will also escape the string.

 

번역:

클라이언트측에서 처리할 수 있는 답변이 꽤 많지만, 원한다면 출력 서버측을 변경할 수 있다.
여기에 접근하는 방법에는 몇 가지가 있는데, 기본부터 짚어보겠다. JsonResult 클래스를 하위 클래스로 분류하고 ExecuteResult 메소드를 재정의하십시오. 거기서 당신은 연재물을 바꾸기 위해 몇 가지 다른 접근법을 취할 수 있다.
접근 1:
기본 구현은 을 사용한다. 설명서를 보면 RegisterConverters 방법을 사용하여 사용자 정의 를 추가할 수 있다. 그러나 다음과 같은 몇 가지 문제가 있다. JavaScriptConverter는 사전을 연재한다. 즉, 사물을 가져다가 Json 사전을 연재한다. 객체를 문자열로 직렬화하려면 약간의 진부함이 필요하다( 참조 이 특별한 해킹은 또한 끈에서 벗어날 것이다.

public class CustomJsonResult : JsonResult
{
    private const string _dateFormat = "yyyy-MM-dd HH:mm:ss";

    public override void ExecuteResult(ControllerContext context)
    {
        if (context == null)
        {
            throw new ArgumentNullException("context");
        }

        HttpResponseBase response = context.HttpContext.Response;

        if (!String.IsNullOrEmpty(ContentType))
        {
            response.ContentType = ContentType;
        }
        else
        {
            response.ContentType = "application/json";
        }
        if (ContentEncoding != null)
        {
            response.ContentEncoding = ContentEncoding;
        }
        if (Data != null)
        {
            JavaScriptSerializer serializer = new JavaScriptSerializer();

            // Use your custom JavaScriptConverter subclass here.
            serializer.RegisterConverters(new JavascriptConverter[] { new CustomConverter });

            response.Write(serializer.Serialize(Data));
        }
    }
}

Approach 2 (recommended): The second approach is to start with the overridden JsonResult and go with another Json serializer, in my case the serializer. This doesn't require the hackery of approach 1. Here is my implementation of the JsonResult subclass:

 

번역: 

접근 2(권장): 두 번째 방법은 오버라이드된 JsonResult부터 시작해서 다른 Json serializer, 내 경우 serializer로 가는 것이다. 이것은 접근 1의 속임수를 필요로 하지 않는다. JsonResult 하위 클래스에 대한 구현:

 

public class CustomJsonResult : JsonResult
{
    private const string _dateFormat = "yyyy-MM-dd HH:mm:ss";

    public override void ExecuteResult(ControllerContext context)
    {
        if (context == null)
        {
            throw new ArgumentNullException("context");
        }

        HttpResponseBase response = context.HttpContext.Response;

        if (!String.IsNullOrEmpty(ContentType))
        {
            response.ContentType = ContentType;
        }
        else
        {
            response.ContentType = "application/json";
        }
        if (ContentEncoding != null)
        {
            response.ContentEncoding = ContentEncoding;
        }
        if (Data != null)
        {
            // Using Json.NET serializer
            var isoConvert = new IsoDateTimeConverter();
            isoConvert.DateTimeFormat = _dateFormat;
            response.Write(JsonConvert.SerializeObject(Data, isoConvert));
        }
    }
}

Usage Example:

[HttpGet]
public ActionResult Index() {
    return new CustomJsonResult { Data = new { users=db.Users.ToList(); } };
}

 

매우매우 유용한 답변이다. Json은 date타입을 파싱하지 못하는데 클라이언트측에서해결하는 방식이 아닌 서버단에서 해결하는 방식으로 매우매우 유용하다. 

 

출처 : https://stackoverflow.com/questions/726334/asp-net-mvc-jsonresult-date-format

반응형

+ Recent posts