문제

나는 ASP.NET MVC를 처음 접 했으므로 가능한 한 귀하의 답변에서 설명 적으로 설명하십시오 :)

내가하려는 일을 단순화하겠습니다. 자동차에 대한 정보를 입력하고 싶은 양식이 있다고 상상해보십시오. 필드는 Make, Model, Year, Image1, Image2 일 수 있습니다.

양식의 하단에는 "저장"버튼이 있습니다. 관련 컨트롤러 방법은 Image1 및 Image2를 디스크에 저장하고 파일 이름을 얻은 다음 자동차 모델과 연결 한 다음 데이터베이스에 저장됩니다.

어떤 아이디어?

감사합니다!

편집하다

WINOB0T 저를 대부분 얻었습니다. 뛰어난 문제는 다음과 같습니다. Image1 및 Image2는 필드가 필요하지 않으므로 이제 0,1 또는 2 개의 이미지를 저장할 수 있습니다. 그러나 사용자가 1 사진 만 업로드하는 경우 ImageUpload1 또는 ImageUpload2에서 온 것인지 알 수있는 방법이 없습니다.

다시, 모든 도움이 감사합니다!

도움이 되었습니까?

해결책

컨트롤러에서 업로드 된 파일에 다음과 같이 액세스 할 수 있습니다.

    if(Request.Files.Count > 0 && Request.Files[0].ContentLength > 0) {
        HttpPostedFileBase postFile = Request.Files.Get(0);
        string filename = GenerateUniqueFileName(postFile.FileName);
        postFile.SaveAs(server.MapPath(FileDirectoryPath + filename));
    }

protected virtual string GenerateUniqueFileName(string filename) {

    // get the extension
    string ext = Path.GetExtension(filename);
    string newFileName = "";

    // generate filename, until it's a unique filename
    bool unique = false;

    do {
        Random r = new Random();
        newFileName = Path.GetFileNameWithoutExtension(filename) + "_" + r.Next().ToString() + ext;
        unique = !File.Exists(FileDirectoryPath + newFileName);
    } while(!unique);
    return newFileName;
}

텍스트 필드는 일반적인 request.form [...]에 따라 컨트롤러 작업에 도달합니다. 또한 양식에 ENCTEPE를 "Multipart/Form-Data"로 설정해야합니다. ASP.NET MVC에 대해 나머지 작업을 수행 할만 큼 충분히 이해하는 것 같습니다. 또한 ASPX보기에서 다음과 같이 양식 태그를 선언 할 수 있지만 원하는 경우 더 전통적인 접근 방식을 사용할 수 있습니다.

<% using(Html.BeginForm<FooController>(c => c.Submit(), FormMethod.Post, new { enctype = "multipart/form-data", @id = formId, @class = "submitItem" })) { %> 

<% } %>

다른 팁

여기 내 해결책이 있습니다. 위의 답변은 내 상황에 효과적이지 않았습니다. 양식 세부 사항에 대해 아무것도 신경 쓰지 않으며 여러 업로드를 허용합니다.

    for (int i = (Request.Files.Count - 1); i >= 0; i--)
    {
          if (Request.Files != null && Request.Files[i].ContentLength > 0)
          {
               string path = this.Server.MapPath("~/Content/images/");
               string filename = Path.GetFileName(Request.Files[i].FileName);
               string fullpath = Path.Combine(path, filename);
               Request.Files[i].SaveAs(fullpath);
           }
     }
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top