From 643142acab44d46aa6c001c90ad5d307a8662b99 Mon Sep 17 00:00:00 2001
From: Unknwon <u@gogs.io>
Date: Tue, 30 Aug 2016 05:07:50 -0700
Subject: [PATCH] Web editor: support upload files

---
 README.md                              |   2 +-
 cmd/web.go                             |  16 +-
 conf/app.ini                           |   8 +-
 conf/locale/locale_en-US.ini           |   8 +-
 gogs.go                                |   2 +-
 models/error.go                        |   8 +-
 models/issue.go                        |  15 +-
 models/models.go                       |   2 +-
 models/pull.go                         |   6 +-
 models/repo.go                         | 194 -------------------
 models/repo_editor.go                  | 227 ++++++++++++++++++++++
 modules/auth/repo_form.go              |   2 +-
 modules/template/template.go           |   1 +
 public/css/gogs.css                    |   8 +-
 public/less/_repository.less           |   6 +-
 routers/repo/editor.go                 | 199 +++++++++++++++++--
 routers/repo/issue.go                  |   2 +-
 routers/repo/upload.go                 | 253 -------------------------
 routers/repo/view.go                   |   7 +-
 templates/.VERSION                     |   2 +-
 templates/repo/editor/commit_form.tmpl |   2 +-
 templates/repo/editor/upload.tmpl      |  36 ++++
 templates/repo/home.tmpl               |  18 +-
 templates/repo/upload.tmpl             |  79 --------
 24 files changed, 503 insertions(+), 600 deletions(-)
 delete mode 100644 routers/repo/upload.go
 create mode 100644 templates/repo/editor/upload.tmpl
 delete mode 100644 templates/repo/upload.tmpl

diff --git a/README.md b/README.md
index 093888749c..ce5c0b612b 100644
--- a/README.md
+++ b/README.md
@@ -3,7 +3,7 @@ Gogs - Go Git Service [![Build Status](https://travis-ci.org/gogits/gogs.svg?bra
 
 ![](https://github.com/gogits/gogs/blob/master/public/img/gogs-large-resize.png?raw=true)
 
-##### Current tip version: 0.9.94 (see [Releases](https://github.com/gogits/gogs/releases) for binary versions)
+##### Current tip version: 0.9.95 (see [Releases](https://github.com/gogits/gogs/releases) for binary versions)
 
 | Web | UI  | Preview  |
 |:-------------:|:-------:|:-------:|
diff --git a/cmd/web.go b/cmd/web.go
index 3a1108a45c..92e7fef423 100644
--- a/cmd/web.go
+++ b/cmd/web.go
@@ -505,12 +505,20 @@ func runWeb(ctx *cli.Context) error {
 			m.Combo("/_new/*").Get(repo.NewFile).
 				Post(bindIgnErr(auth.EditRepoFileForm{}), repo.NewFilePost)
 			m.Post("/_preview/*", bindIgnErr(auth.EditPreviewDiffForm{}), repo.DiffPreviewPost)
-			m.Combo("/_upload/*").Get(repo.UploadFile).
-				Post(bindIgnErr(auth.UploadRepoFileForm{}), repo.UploadFilePost)
 			m.Combo("/_delete/*").Get(repo.DeleteFile).
 				Post(bindIgnErr(auth.DeleteRepoFileForm{}), repo.DeleteFilePost)
-			// m.Post("/upload-file", repo.UploadFileToServer)
-			// m.Post("/upload-remove", bindIgnErr(auth.RemoveUploadFileForm{}), repo.RemoveUploadFileFromServer)
+
+			m.Group("", func() {
+				m.Combo("/_upload/*").Get(repo.UploadFile).
+					Post(bindIgnErr(auth.UploadRepoFileForm{}), repo.UploadFilePost)
+				m.Post("/upload-file", repo.UploadFileToServer)
+				m.Post("/upload-remove", bindIgnErr(auth.RemoveUploadFileForm{}), repo.RemoveUploadFileFromServer)
+			}, func(ctx *context.Context) {
+				if !setting.Repository.Upload.Enabled {
+					ctx.Handle(404, "", nil)
+					return
+				}
+			})
 		}, reqRepoWriter, context.RepoRef(), func(ctx *context.Context) {
 			if !ctx.Repo.Repository.CanEnableEditor() || ctx.Repo.IsViewCommit {
 				ctx.Handle(404, "", nil)
diff --git a/conf/app.ini b/conf/app.ini
index 5206d4c3be..3287775491 100644
--- a/conf/app.ini
+++ b/conf/app.ini
@@ -38,10 +38,10 @@ ENABLED = true
 TEMP_PATH = data/tmp/uploads
 ; One or more allowed types, e.g. image/jpeg|image/png. Nothing means any file type
 ALLOWED_TYPES =
-; Max size of each file in MB. Defaults to 32MB
-FILE_MAX_SIZE = 32
-; Max number of files per upload. Defaults to 10
-MAX_FILES = 10
+; Max size of each file in MB. Defaults to 3MB
+FILE_MAX_SIZE = 3
+; Max number of files per upload. Defaults to 5
+MAX_FILES = 5
 
 [ui]
 ; Number of repositories that are showed in one explore page
diff --git a/conf/locale/locale_en-US.ini b/conf/locale/locale_en-US.ini
index 2aa2bf0d60..d2ffde68c5 100644
--- a/conf/locale/locale_en-US.ini
+++ b/conf/locale/locale_en-US.ini
@@ -427,6 +427,7 @@ file_permalink = Permalink
 file_too_large = This file is too large to be shown
 
 editor.new_file = New file
+editor.upload_file = Upload file
 editor.edit_file = Edit file
 editor.preview_changes = Preview Changes
 editor.cannot_edit_non_text_files = Cannot edit non-text files
@@ -459,10 +460,9 @@ editor.file_changed_while_editing = File content has been changed since you star
 editor.file_already_exists = A file with name '%s' already exists in this repository.
 editor.no_changes_to_show = There are no changes to show.
 editor.fail_to_update_file = Failed to update/create file '%s' with error: %v
-upload_files = Upload files
-upload_file = Upload file
-add_files_to_dir = Add files to %s
-add_subdir = Add subdirectory...
+editor.add_subdir = Add subdirectory...
+editor.unable_to_upload_files = Failed to upload files to '%s' with error: %v
+editor.upload_files_to_dir = Upload files to '%s'
 
 commits.commits = Commits
 commits.search = Search commits
diff --git a/gogs.go b/gogs.go
index 369ef99303..3dd7add7ad 100644
--- a/gogs.go
+++ b/gogs.go
@@ -17,7 +17,7 @@ import (
 	"github.com/gogits/gogs/modules/setting"
 )
 
-const APP_VER = "0.9.94.0830"
+const APP_VER = "0.9.95.0830"
 
 func init() {
 	runtime.GOMAXPROCS(runtime.NumCPU())
diff --git a/models/error.go b/models/error.go
index 240e606776..dd1d4a668d 100644
--- a/models/error.go
+++ b/models/error.go
@@ -652,10 +652,8 @@ func (err ErrTeamAlreadyExist) Error() string {
 //
 
 type ErrUploadNotExist struct {
-	ID     int64
-	UUID   string
-	UserID int64
-	RepoID int64
+	ID   int64
+	UUID string
 }
 
 func IsErrUploadNotExist(err error) bool {
@@ -664,5 +662,5 @@ func IsErrUploadNotExist(err error) bool {
 }
 
 func (err ErrUploadNotExist) Error() string {
-	return fmt.Sprintf("attachment does not exist [id: %d, uuid: %s, user_id: %d, repo_id: %d]", err.ID, err.UUID, err.UserID, err.RepoID)
+	return fmt.Sprintf("attachment does not exist [id: %d, uuid: %s]", err.ID, err.UUID)
 }
diff --git a/models/issue.go b/models/issue.go
index a90ebaf866..208204b076 100644
--- a/models/issue.go
+++ b/models/issue.go
@@ -1685,11 +1685,12 @@ func NewAttachment(name string, buf []byte, file multipart.File) (_ *Attachment,
 		Name: name,
 	}
 
-	if err = os.MkdirAll(path.Dir(attach.LocalPath()), os.ModePerm); err != nil {
+	localPath := attach.LocalPath()
+	if err = os.MkdirAll(path.Dir(localPath), os.ModePerm); err != nil {
 		return nil, fmt.Errorf("MkdirAll: %v", err)
 	}
 
-	fw, err := os.Create(attach.LocalPath())
+	fw, err := os.Create(localPath)
 	if err != nil {
 		return nil, fmt.Errorf("Create: %v", err)
 	}
@@ -1701,17 +1702,11 @@ func NewAttachment(name string, buf []byte, file multipart.File) (_ *Attachment,
 		return nil, fmt.Errorf("Copy: %v", err)
 	}
 
-	sess := x.NewSession()
-	defer sessionRelease(sess)
-	if err := sess.Begin(); err != nil {
+	if _, err := x.Insert(attach); err != nil {
 		return nil, err
 	}
 
-	if _, err := sess.Insert(attach); err != nil {
-		return nil, err
-	}
-
-	return attach, sess.Commit()
+	return attach, nil
 }
 
 func getAttachmentByUUID(e Engine, uuid string) (*Attachment, error) {
diff --git a/models/models.go b/models/models.go
index 582c4403ad..481e53e36e 100644
--- a/models/models.go
+++ b/models/models.go
@@ -60,7 +60,7 @@ var (
 func init() {
 	tables = append(tables,
 		new(User), new(PublicKey), new(AccessToken),
-		new(Repository), new(DeployKey), new(Collaboration), new(Access),
+		new(Repository), new(DeployKey), new(Collaboration), new(Access), new(Upload),
 		new(Watch), new(Star), new(Follow), new(Action),
 		new(Issue), new(PullRequest), new(Comment), new(Attachment), new(IssueUser),
 		new(Label), new(IssueLabel), new(Milestone),
diff --git a/models/pull.go b/models/pull.go
index fa9a44897a..64b347554c 100644
--- a/models/pull.go
+++ b/models/pull.go
@@ -339,9 +339,6 @@ var patchConflicts = []string{
 // testPatch checks if patch can be merged to base repository without conflit.
 // FIXME: make a mechanism to clean up stable local copies.
 func (pr *PullRequest) testPatch() (err error) {
-	repoWorkingPool.CheckIn(com.ToStr(pr.BaseRepoID))
-	defer repoWorkingPool.CheckOut(com.ToStr(pr.BaseRepoID))
-
 	if pr.BaseRepo == nil {
 		pr.BaseRepo, err = GetRepositoryByID(pr.BaseRepoID)
 		if err != nil {
@@ -360,6 +357,9 @@ func (pr *PullRequest) testPatch() (err error) {
 		return nil
 	}
 
+	repoWorkingPool.CheckIn(com.ToStr(pr.BaseRepoID))
+	defer repoWorkingPool.CheckOut(com.ToStr(pr.BaseRepoID))
+
 	log.Trace("PullRequest[%d].testPatch (patchPath): %s", pr.ID, patchPath)
 
 	if err := pr.BaseRepo.UpdateLocalCopyBranch(pr.BaseBranch); err != nil {
diff --git a/models/repo.go b/models/repo.go
index 2c19afbd17..a26ba92482 100644
--- a/models/repo.go
+++ b/models/repo.go
@@ -9,9 +9,7 @@ import (
 	"errors"
 	"fmt"
 	"html/template"
-	"io"
 	"io/ioutil"
-	"mime/multipart"
 	"os"
 	"os/exec"
 	"path"
@@ -29,7 +27,6 @@ import (
 
 	git "github.com/gogits/git-module"
 	api "github.com/gogits/go-gogs-client"
-	gouuid "github.com/satori/go.uuid"
 
 	"github.com/gogits/gogs/modules/bindata"
 	"github.com/gogits/gogs/modules/log"
@@ -2272,197 +2269,6 @@ func (repo *Repository) GetForks() ([]*Repository, error) {
 	return forks, x.Find(&forks, &Repository{ForkID: repo.ID})
 }
 
-//  ____ ___        .__                    .___ ___________.___.__
-// |    |   \______ |  |   _________     __| _/ \_   _____/|   |  |   ____   ______
-// |    |   /\____ \|  |  /  _ \__  \   / __ |   |    __)  |   |  | _/ __ \ /  ___/
-// |    |  / |  |_> >  |_(  <_> ) __ \_/ /_/ |   |     \   |   |  |_\  ___/ \___ \
-// |______/  |   __/|____/\____(____  /\____ |   \___  /   |___|____/\___  >____  >
-//           |__|                   \/      \/       \/                  \/     \/
-//
-
-// uploadRepoFiles uploads new files to repository.
-func (repo *Repository) UploadRepoFiles(doer *User, oldBranchName, branchName, treePath, message string, uuids []string) (err error) {
-	repoWorkingPool.CheckIn(com.ToStr(repo.ID))
-	defer repoWorkingPool.CheckOut(com.ToStr(repo.ID))
-
-	localPath := repo.LocalCopyPath()
-
-	if err = discardLocalRepoBranchChanges(localPath, oldBranchName); err != nil {
-		return fmt.Errorf("discardLocalRepoChanges: %v", err)
-	} else if err = repo.UpdateLocalCopyBranch(oldBranchName); err != nil {
-		return fmt.Errorf("UpdateLocalCopyBranch: %v", err)
-	}
-
-	if oldBranchName != branchName {
-		repo.CheckoutNewBranch(oldBranchName, branchName)
-	}
-
-	dirPath := path.Join(localPath, treePath)
-	os.MkdirAll(dirPath, os.ModePerm)
-
-	// Copy uploaded files into repository.
-	for _, uuid := range uuids {
-		upload, err := getUpload(uuid, doer.ID, repo.ID)
-		if err != nil {
-			if IsErrUploadNotExist(err) {
-				continue
-			}
-			return fmt.Errorf("getUpload[%s]: %v", uuid, err)
-		}
-		uuidPath := upload.LocalPath()
-		filePath := dirPath + "/" + upload.Name
-		if err := os.Rename(uuidPath, filePath); err != nil {
-			DeleteUpload(upload, true)
-			return fmt.Errorf("Rename[%s -> %s]: %v", uuidPath, filePath, err)
-		}
-		DeleteUpload(upload, false) // false because we have moved the file
-	}
-
-	if len(message) == 0 {
-		message = "Add files to '" + treePath + "'"
-	}
-
-	if err = git.AddChanges(localPath, true); err != nil {
-		return fmt.Errorf("AddChanges: %v", err)
-	} else if err = git.CommitChanges(localPath, git.CommitChangesOptions{
-		Committer: doer.NewGitSig(),
-		Message:   message,
-	}); err != nil {
-		return fmt.Errorf("CommitChanges: %v", err)
-	} else if err = git.Push(localPath, "origin", branchName); err != nil {
-		return fmt.Errorf("Push: %v", err)
-	}
-
-	return nil
-}
-
-// Upload represent a uploaded file to a repo to be deleted when moved
-type Upload struct {
-	ID          int64  `xorm:"pk autoincr"`
-	UUID        string `xorm:"uuid UNIQUE"`
-	UID         int64  `xorm:"INDEX"`
-	RepoID      int64  `xorm:"INDEX"`
-	Name        string
-	Created     time.Time `xorm:"-"`
-	CreatedUnix int64
-}
-
-func (u *Upload) BeforeInsert() {
-	u.CreatedUnix = time.Now().UTC().Unix()
-}
-
-func (u *Upload) AfterSet(colName string, _ xorm.Cell) {
-	switch colName {
-	case "created_unix":
-		u.Created = time.Unix(u.CreatedUnix, 0).Local()
-	}
-}
-
-// UploadLocalPath returns where uploads is stored in local file system based on given UUID.
-func UploadLocalPath(uuid string) string {
-	return path.Join(setting.Repository.Upload.TempPath, uuid[0:1], uuid[1:2], uuid)
-}
-
-// LocalPath returns where uploads are temporarily stored in local file system.
-func (upload *Upload) LocalPath() string {
-	return UploadLocalPath(upload.UUID)
-}
-
-// NewUpload creates a new upload object.
-func NewUpload(name string, buf []byte, file multipart.File, userId, repoId int64) (_ *Upload, err error) {
-	up := &Upload{
-		UUID:   gouuid.NewV4().String(),
-		Name:   name,
-		UID:    userId,
-		RepoID: repoId,
-	}
-
-	if err = os.MkdirAll(path.Dir(up.LocalPath()), os.ModePerm); err != nil {
-		return nil, fmt.Errorf("MkdirAll: %v", err)
-	}
-
-	fw, err := os.Create(up.LocalPath())
-	if err != nil {
-		return nil, fmt.Errorf("Create: %v", err)
-	}
-	defer fw.Close()
-
-	if _, err = fw.Write(buf); err != nil {
-		return nil, fmt.Errorf("Write: %v", err)
-	} else if _, err = io.Copy(fw, file); err != nil {
-		return nil, fmt.Errorf("Copy: %v", err)
-	}
-
-	sess := x.NewSession()
-	defer sessionRelease(sess)
-	if err := sess.Begin(); err != nil {
-		return nil, err
-	}
-	if _, err := sess.Insert(up); err != nil {
-		return nil, err
-	}
-
-	return up, sess.Commit()
-}
-
-// RemoveUpload removes the file by UUID
-func RemoveUpload(uuid string, userId, repoId int64) (err error) {
-	sess := x.NewSession()
-	defer sessionRelease(sess)
-	if err := sess.Begin(); err != nil {
-		return err
-	}
-	upload, err := getUpload(uuid, userId, repoId)
-	if err != nil {
-		return fmt.Errorf("getUpload[%s]: %v", uuid, err)
-	}
-
-	if err := DeleteUpload(upload, true); err != nil {
-		return fmt.Errorf("DeleteUpload[%s]: %v", uuid, err)
-	}
-
-	return nil
-}
-
-func getUpload(uuid string, userID, repoID int64) (*Upload, error) {
-	up := &Upload{UUID: uuid, UID: userID, RepoID: repoID}
-	has, err := x.Get(up)
-	if err != nil {
-		return nil, err
-	} else if !has {
-		return nil, ErrUploadNotExist{0, uuid, userID, repoID}
-	}
-	return up, nil
-}
-
-// GetUpload returns Upload by given UUID.
-func GetUpload(uuid string, userId, repoId int64) (*Upload, error) {
-	return getUpload(uuid, userId, repoId)
-}
-
-// DeleteUpload deletes the given upload
-func DeleteUpload(u *Upload, remove bool) error {
-	_, err := DeleteUploads([]*Upload{u}, remove)
-	return err
-}
-
-// DeleteUploads deletes the given uploads
-func DeleteUploads(uploads []*Upload, remove bool) (int, error) {
-	for i, u := range uploads {
-		if remove {
-			if err := os.Remove(u.LocalPath()); err != nil {
-				return i, err
-			}
-		}
-
-		if _, err := x.Delete(u); err != nil {
-			return i, err
-		}
-	}
-
-	return len(uploads), nil
-}
-
 // __________                             .__
 // \______   \____________    ____   ____ |  |__
 //  |    |  _/\_  __ \__  \  /    \_/ ___\|  |  \
diff --git a/models/repo_editor.go b/models/repo_editor.go
index 31b94f631e..dfdb864a1c 100644
--- a/models/repo_editor.go
+++ b/models/repo_editor.go
@@ -6,7 +6,9 @@ package models
 
 import (
 	"fmt"
+	"io"
 	"io/ioutil"
+	"mime/multipart"
 	"os"
 	"os/exec"
 	"path"
@@ -14,6 +16,7 @@ import (
 	"time"
 
 	"github.com/Unknwon/com"
+	gouuid "github.com/satori/go.uuid"
 
 	git "github.com/gogits/git-module"
 
@@ -291,3 +294,227 @@ func (repo *Repository) DeleteRepoFile(doer *User, opts DeleteRepoFileOptions) (
 
 	return nil
 }
+
+//  ____ ___        .__                    .___ ___________.___.__
+// |    |   \______ |  |   _________     __| _/ \_   _____/|   |  |   ____   ______
+// |    |   /\____ \|  |  /  _ \__  \   / __ |   |    __)  |   |  | _/ __ \ /  ___/
+// |    |  / |  |_> >  |_(  <_> ) __ \_/ /_/ |   |     \   |   |  |_\  ___/ \___ \
+// |______/  |   __/|____/\____(____  /\____ |   \___  /   |___|____/\___  >____  >
+//           |__|                   \/      \/       \/                  \/     \/
+//
+
+// Upload represent a uploaded file to a repo to be deleted when moved
+type Upload struct {
+	ID   int64  `xorm:"pk autoincr"`
+	UUID string `xorm:"uuid UNIQUE"`
+	Name string
+}
+
+// UploadLocalPath returns where uploads is stored in local file system based on given UUID.
+func UploadLocalPath(uuid string) string {
+	return path.Join(setting.Repository.Upload.TempPath, uuid[0:1], uuid[1:2], uuid)
+}
+
+// LocalPath returns where uploads are temporarily stored in local file system.
+func (upload *Upload) LocalPath() string {
+	return UploadLocalPath(upload.UUID)
+}
+
+// NewUpload creates a new upload object.
+func NewUpload(name string, buf []byte, file multipart.File) (_ *Upload, err error) {
+	upload := &Upload{
+		UUID: gouuid.NewV4().String(),
+		Name: name,
+	}
+
+	localPath := upload.LocalPath()
+	if err = os.MkdirAll(path.Dir(localPath), os.ModePerm); err != nil {
+		return nil, fmt.Errorf("MkdirAll: %v", err)
+	}
+
+	fw, err := os.Create(localPath)
+	if err != nil {
+		return nil, fmt.Errorf("Create: %v", err)
+	}
+	defer fw.Close()
+
+	if _, err = fw.Write(buf); err != nil {
+		return nil, fmt.Errorf("Write: %v", err)
+	} else if _, err = io.Copy(fw, file); err != nil {
+		return nil, fmt.Errorf("Copy: %v", err)
+	}
+
+	if _, err := x.Insert(upload); err != nil {
+		return nil, err
+	}
+
+	return upload, nil
+}
+
+func GetUploadByUUID(uuid string) (*Upload, error) {
+	upload := &Upload{UUID: uuid}
+	has, err := x.Get(upload)
+	if err != nil {
+		return nil, err
+	} else if !has {
+		return nil, ErrUploadNotExist{0, uuid}
+	}
+	return upload, nil
+}
+
+func GetUploadsByUUIDs(uuids []string) ([]*Upload, error) {
+	if len(uuids) == 0 {
+		return []*Upload{}, nil
+	}
+
+	// Silently drop invalid uuids.
+	uploads := make([]*Upload, 0, len(uuids))
+	return uploads, x.In("uuid", uuids).Find(&uploads)
+}
+
+func DeleteUploads(uploads ...*Upload) (err error) {
+	if len(uploads) == 0 {
+		return nil
+	}
+
+	sess := x.NewSession()
+	defer sessionRelease(sess)
+	if err = sess.Begin(); err != nil {
+		return err
+	}
+
+	ids := make([]int64, len(uploads))
+	for i := 0; i < len(uploads); i++ {
+		ids[i] = uploads[i].ID
+	}
+	if _, err = sess.In("id", ids).Delete(new(Upload)); err != nil {
+		return fmt.Errorf("delete uploads: %v", err)
+	}
+
+	for _, upload := range uploads {
+		localPath := upload.LocalPath()
+		if !com.IsFile(localPath) {
+			continue
+		}
+
+		if err := os.Remove(localPath); err != nil {
+			return fmt.Errorf("remove upload: %v", err)
+		}
+	}
+
+	return sess.Commit()
+}
+
+func DeleteUpload(u *Upload) error {
+	return DeleteUploads(u)
+}
+
+func DeleteUploadByUUID(uuid string) error {
+	upload, err := GetUploadByUUID(uuid)
+	if err != nil {
+		if IsErrUploadNotExist(err) {
+			return nil
+		}
+		return fmt.Errorf("GetUploadByUUID: %v", err)
+	}
+
+	if err := DeleteUpload(upload); err != nil {
+		return fmt.Errorf("DeleteUpload: %v", err)
+	}
+
+	return nil
+}
+
+type UploadRepoFileOptions struct {
+	LastCommitID string
+	OldBranch    string
+	NewBranch    string
+	TreePath     string
+	Message      string
+	Files        []string // In UUID format.
+}
+
+func (repo *Repository) UploadRepoFiles(doer *User, opts UploadRepoFileOptions) (err error) {
+	if len(opts.Files) == 0 {
+		return nil
+	}
+
+	uploads, err := GetUploadsByUUIDs(opts.Files)
+	if err != nil {
+		return fmt.Errorf("GetUploadsByUUIDs [uuids: %v]: %v", opts.Files, err)
+	}
+
+	repoWorkingPool.CheckIn(com.ToStr(repo.ID))
+	defer repoWorkingPool.CheckOut(com.ToStr(repo.ID))
+
+	if err = repo.DiscardLocalRepoBranchChanges(opts.OldBranch); err != nil {
+		return fmt.Errorf("DiscardLocalRepoBranchChanges [branch: %s]: %v", opts.OldBranch, err)
+	} else if err = repo.UpdateLocalCopyBranch(opts.OldBranch); err != nil {
+		return fmt.Errorf("UpdateLocalCopyBranch [branch: %s]: %v", opts.OldBranch, err)
+	}
+
+	if opts.OldBranch != opts.NewBranch {
+		if err = repo.CheckoutNewBranch(opts.OldBranch, opts.NewBranch); err != nil {
+			return fmt.Errorf("CheckoutNewBranch [old_branch: %s, new_branch: %s]: %v", opts.OldBranch, opts.NewBranch, err)
+		}
+	}
+
+	localPath := repo.LocalCopyPath()
+	dirPath := path.Join(localPath, opts.TreePath)
+	os.MkdirAll(dirPath, os.ModePerm)
+
+	// Copy uploaded files into repository.
+	for _, upload := range uploads {
+		tmpPath := upload.LocalPath()
+		targetPath := path.Join(dirPath, upload.Name)
+		if !com.IsFile(tmpPath) {
+			continue
+		}
+
+		if err = com.Copy(tmpPath, targetPath); err != nil {
+			return fmt.Errorf("Copy: %v", err)
+		}
+	}
+
+	if err = git.AddChanges(localPath, true); err != nil {
+		return fmt.Errorf("git add --all: %v", err)
+	} else if err = git.CommitChanges(localPath, git.CommitChangesOptions{
+		Committer: doer.NewGitSig(),
+		Message:   opts.Message,
+	}); err != nil {
+		return fmt.Errorf("CommitChanges: %v", err)
+	} else if err = git.Push(localPath, "origin", opts.NewBranch); err != nil {
+		return fmt.Errorf("git push origin %s: %v", opts.NewBranch, err)
+	}
+
+	gitRepo, err := git.OpenRepository(repo.RepoPath())
+	if err != nil {
+		log.Error(4, "OpenRepository: %v", err)
+		return nil
+	}
+	commit, err := gitRepo.GetBranchCommit(opts.NewBranch)
+	if err != nil {
+		log.Error(4, "GetBranchCommit [branch: %s]: %v", opts.NewBranch, err)
+		return nil
+	}
+
+	// Simulate push event.
+	pushCommits := &PushCommits{
+		Len:     1,
+		Commits: []*PushCommit{CommitToPushCommit(commit)},
+	}
+	if err := CommitRepoAction(CommitRepoActionOptions{
+		PusherName:  doer.Name,
+		RepoOwnerID: repo.MustOwner().ID,
+		RepoName:    repo.Name,
+		RefFullName: git.BRANCH_PREFIX + opts.NewBranch,
+		OldCommitID: opts.LastCommitID,
+		NewCommitID: commit.ID.String(),
+		Commits:     pushCommits,
+	}); err != nil {
+		log.Error(4, "CommitRepoAction: %v", err)
+		return nil
+	}
+
+	return DeleteUploads(uploads...)
+}
diff --git a/modules/auth/repo_form.go b/modules/auth/repo_form.go
index 0ed4c1b22a..d1e28dc119 100644
--- a/modules/auth/repo_form.go
+++ b/modules/auth/repo_form.go
@@ -316,7 +316,7 @@ func (f *EditPreviewDiffForm) Validate(ctx *macaron.Context, errs binding.Errors
 //
 
 type UploadRepoFileForm struct {
-	TreeName      string `binding:MaxSize(500)"`
+	TreePath      string `binding:MaxSize(500)"`
 	CommitSummary string `binding:"MaxSize(100)`
 	CommitMessage string
 	CommitChoice  string `binding:"Required;MaxSize(50)"`
diff --git a/modules/template/template.go b/modules/template/template.go
index 433c412787..707697df34 100644
--- a/modules/template/template.go
+++ b/modules/template/template.go
@@ -86,6 +86,7 @@ func NewFuncMap() []template.FuncMap {
 			}
 			return str[start:end]
 		},
+		"EllipsisString":    base.EllipsisString,
 		"DiffTypeToStr":     DiffTypeToStr,
 		"DiffLineTypeToStr": DiffLineTypeToStr,
 		"Sha1":              Sha1,
diff --git a/public/css/gogs.css b/public/css/gogs.css
index d95f0b423b..9e3b92fa57 100644
--- a/public/css/gogs.css
+++ b/public/css/gogs.css
@@ -1198,8 +1198,8 @@ footer .ui.language .menu {
 }
 .repository #clone-panel {
   margin-top: -8px;
-  width: 100%;
-  padding-left: 20px;
+  margin-left: 5px;
+  width: 350px;
 }
 .repository #clone-panel input {
   border-radius: 0;
@@ -2270,13 +2270,13 @@ footer .ui.language .menu {
 .page.buttons {
   padding-top: 15px;
 }
-.ui.comments .dropzone {
+.ui.form .dropzone {
   width: 100%;
   margin-bottom: 10px;
   border: 2px dashed #0087F7;
   box-shadow: none!important;
 }
-.ui.comments .dropzone .dz-error-message {
+.ui.form .dropzone .dz-error-message {
   top: 140px;
 }
 .settings .content {
diff --git a/public/less/_repository.less b/public/less/_repository.less
index 24a0bfa013..dbbffdfeb2 100644
--- a/public/less/_repository.less
+++ b/public/less/_repository.less
@@ -126,8 +126,8 @@
 
 	#clone-panel {
 		margin-top: -8px;
-		width: 100%;
-		padding-left: 20px;
+		margin-left: 5px;
+		width: 350px;
 
 		input {
 			border-radius: 0;
@@ -1303,7 +1303,7 @@
 	padding-top: 15px;
 }
 
-.ui.comments {
+.ui.form {
 	.dropzone {
 		width: 100%;
 		margin-bottom: 10px;
diff --git a/routers/repo/editor.go b/routers/repo/editor.go
index 465de00214..f471e5ee22 100644
--- a/routers/repo/editor.go
+++ b/routers/repo/editor.go
@@ -5,7 +5,9 @@
 package repo
 
 import (
+	"fmt"
 	"io/ioutil"
+	"net/http"
 	"path"
 	"strings"
 
@@ -23,6 +25,7 @@ const (
 	EDIT_FILE         base.TplName = "repo/editor/edit"
 	EDIT_DIFF_PREVIEW base.TplName = "repo/editor/diff_preview"
 	DELETE_FILE       base.TplName = "repo/editor/delete"
+	UPLOAD_FILE       base.TplName = "repo/editor/upload"
 )
 
 func editFile(ctx *context.Context, isNewFile bool) {
@@ -31,8 +34,6 @@ func editFile(ctx *context.Context, isNewFile bool) {
 	ctx.Data["RequireHighlightJS"] = true
 	ctx.Data["RequireSimpleMDE"] = true
 
-	branchLink := ctx.Repo.RepoLink + "/src/" + ctx.Repo.BranchName
-
 	var treeNames []string
 	if len(ctx.Repo.TreePath) > 0 {
 		treeNames = strings.Split(ctx.Repo.TreePath, "/")
@@ -41,11 +42,7 @@ func editFile(ctx *context.Context, isNewFile bool) {
 	if !isNewFile {
 		entry, err := ctx.Repo.Commit.GetTreeEntryByPath(ctx.Repo.TreePath)
 		if err != nil {
-			if git.IsErrNotExist(err) {
-				ctx.Handle(404, "GetTreeEntryByPath", err)
-			} else {
-				ctx.Handle(500, "GetTreeEntryByPath", err)
-			}
+			ctx.NotFoundOrServerError("GetTreeEntryByPath", git.IsErrNotExist, err)
 			return
 		}
 
@@ -91,9 +88,8 @@ func editFile(ctx *context.Context, isNewFile bool) {
 		treeNames = append(treeNames, "") // Append empty string to allow user name the new file.
 	}
 
-	ctx.Data["TreePath"] = ctx.Repo.TreePath
 	ctx.Data["TreeNames"] = treeNames
-	ctx.Data["BranchLink"] = branchLink
+	ctx.Data["BranchLink"] = ctx.Repo.RepoLink + "/src/" + ctx.Repo.BranchName
 	ctx.Data["commit_summary"] = ""
 	ctx.Data["commit_message"] = ""
 	ctx.Data["commit_choice"] = "direct"
@@ -122,7 +118,6 @@ func editFilePost(ctx *context.Context, form auth.EditRepoFileForm, isNewFile bo
 
 	oldBranchName := ctx.Repo.BranchName
 	branchName := oldBranchName
-	branchLink := ctx.Repo.RepoLink + "/src/" + branchName
 	oldTreePath := ctx.Repo.TreePath
 	lastCommit := form.LastCommit
 	form.LastCommit = ctx.Repo.Commit.ID.String()
@@ -140,7 +135,7 @@ func editFilePost(ctx *context.Context, form auth.EditRepoFileForm, isNewFile bo
 
 	ctx.Data["TreePath"] = form.TreePath
 	ctx.Data["TreeNames"] = treeNames
-	ctx.Data["BranchLink"] = branchLink
+	ctx.Data["BranchLink"] = ctx.Repo.RepoLink + "/src/" + branchName
 	ctx.Data["FileContent"] = form.Content
 	ctx.Data["commit_summary"] = form.CommitSummary
 	ctx.Data["commit_message"] = form.CommitMessage
@@ -180,7 +175,7 @@ func editFilePost(ctx *context.Context, form auth.EditRepoFileForm, isNewFile bo
 				break
 			}
 
-			ctx.Handle(500, "GetTreeEntryByPath", err)
+			ctx.Handle(500, "Repo.Commit.GetTreeEntryByPath", err)
 			return
 		}
 		if index != len(treeNames)-1 {
@@ -326,7 +321,6 @@ func DeleteFilePost(ctx *context.Context, form auth.DeleteRepoFileForm) {
 
 	oldBranchName := ctx.Repo.BranchName
 	branchName := oldBranchName
-	treePath := ctx.Repo.TreePath
 
 	if form.CommitChoice == "commit-to-new-branch" {
 		branchName = form.NewBranchName
@@ -351,7 +345,7 @@ func DeleteFilePost(ctx *context.Context, form auth.DeleteRepoFileForm) {
 
 	message := strings.TrimSpace(form.CommitSummary)
 	if len(message) == 0 {
-		message = ctx.Tr("repo.editor.delete", treePath)
+		message = ctx.Tr("repo.editor.delete", ctx.Repo.TreePath)
 	}
 
 	form.CommitMessage = strings.TrimSpace(form.CommitMessage)
@@ -363,13 +357,186 @@ func DeleteFilePost(ctx *context.Context, form auth.DeleteRepoFileForm) {
 		LastCommitID: ctx.Repo.CommitID,
 		OldBranch:    oldBranchName,
 		NewBranch:    branchName,
-		TreePath:     treePath,
+		TreePath:     ctx.Repo.TreePath,
 		Message:      message,
 	}); err != nil {
 		ctx.Handle(500, "DeleteRepoFile", err)
 		return
 	}
 
-	ctx.Flash.Success(ctx.Tr("repo.editor.file_delete_success", treePath))
+	ctx.Flash.Success(ctx.Tr("repo.editor.file_delete_success", ctx.Repo.TreePath))
 	ctx.Redirect(ctx.Repo.RepoLink + "/src/" + branchName)
 }
+
+func renderUploadSettings(ctx *context.Context) {
+	ctx.Data["RequireDropzone"] = true
+	ctx.Data["UploadAllowedTypes"] = strings.Join(setting.Repository.Upload.AllowedTypes, ",")
+	ctx.Data["UploadMaxSize"] = setting.Repository.Upload.FileMaxSize
+	ctx.Data["UploadMaxFiles"] = setting.Repository.Upload.MaxFiles
+}
+
+func UploadFile(ctx *context.Context) {
+	ctx.Data["PageIsUpload"] = true
+	renderUploadSettings(ctx)
+
+	// We must at least have one element for user to input.
+	treeNames := []string{""}
+	if len(ctx.Repo.TreePath) > 0 {
+		treeNames = strings.Split(ctx.Repo.TreePath, "/")
+	}
+
+	ctx.Data["TreeNames"] = treeNames
+	ctx.Data["BranchLink"] = ctx.Repo.RepoLink + "/src/" + ctx.Repo.BranchName
+	ctx.Data["commit_summary"] = ""
+	ctx.Data["commit_message"] = ""
+	ctx.Data["commit_choice"] = "direct"
+	ctx.Data["new_branch_name"] = ""
+
+	ctx.HTML(200, UPLOAD_FILE)
+}
+
+func UploadFilePost(ctx *context.Context, form auth.UploadRepoFileForm) {
+	ctx.Data["PageIsUpload"] = true
+	renderUploadSettings(ctx)
+
+	oldBranchName := ctx.Repo.BranchName
+	branchName := oldBranchName
+
+	if form.CommitChoice == "commit-to-new-branch" {
+		branchName = form.NewBranchName
+	}
+
+	form.TreePath = strings.Trim(form.TreePath, " /")
+
+	// We must at least have one element for user to input.
+	treeNames := []string{""}
+	if len(form.TreePath) > 0 {
+		treeNames = strings.Split(form.TreePath, "/")
+	}
+
+	ctx.Data["TreePath"] = form.TreePath
+	ctx.Data["TreeNames"] = treeNames
+	ctx.Data["BranchLink"] = ctx.Repo.RepoLink + "/src/" + branchName
+	ctx.Data["commit_summary"] = form.CommitSummary
+	ctx.Data["commit_message"] = form.CommitMessage
+	ctx.Data["commit_choice"] = form.CommitChoice
+	ctx.Data["new_branch_name"] = branchName
+
+	if ctx.HasError() {
+		ctx.HTML(200, UPLOAD_FILE)
+		return
+	}
+
+	if oldBranchName != branchName {
+		if _, err := ctx.Repo.Repository.GetBranch(branchName); err == nil {
+			ctx.Data["Err_NewBranchName"] = true
+			ctx.RenderWithErr(ctx.Tr("repo.editor.branch_already_exists", branchName), UPLOAD_FILE, &form)
+			return
+		}
+	}
+
+	var newTreePath string
+	for _, part := range treeNames {
+		newTreePath = path.Join(newTreePath, part)
+		entry, err := ctx.Repo.Commit.GetTreeEntryByPath(newTreePath)
+		if err != nil {
+			if git.IsErrNotExist(err) {
+				// Means there is no item with that name, so we're good
+				break
+			}
+
+			ctx.Handle(500, "Repo.Commit.GetTreeEntryByPath", err)
+			return
+		}
+
+		// User can only upload files to a directory.
+		if !entry.IsDir() {
+			ctx.Data["Err_TreePath"] = true
+			ctx.RenderWithErr(ctx.Tr("repo.editor.directory_is_a_file", part), UPLOAD_FILE, &form)
+			return
+		}
+	}
+
+	message := strings.TrimSpace(form.CommitSummary)
+	if len(message) == 0 {
+		message = ctx.Tr("repo.editor.upload_files_to_dir", form.TreePath)
+	}
+
+	form.CommitMessage = strings.TrimSpace(form.CommitMessage)
+	if len(form.CommitMessage) > 0 {
+		message += "\n\n" + form.CommitMessage
+	}
+
+	if err := ctx.Repo.Repository.UploadRepoFiles(ctx.User, models.UploadRepoFileOptions{
+		LastCommitID: ctx.Repo.CommitID,
+		OldBranch:    oldBranchName,
+		NewBranch:    branchName,
+		TreePath:     form.TreePath,
+		Message:      message,
+		Files:        form.Files,
+	}); err != nil {
+		ctx.Data["Err_TreePath"] = true
+		ctx.RenderWithErr(ctx.Tr("repo.editor.unable_to_upload_files", form.TreePath, err), UPLOAD_FILE, &form)
+		return
+	}
+
+	ctx.Redirect(ctx.Repo.RepoLink + "/src/" + branchName + "/" + form.TreePath)
+}
+
+func UploadFileToServer(ctx *context.Context) {
+	file, header, err := ctx.Req.FormFile("file")
+	if err != nil {
+		ctx.Error(500, fmt.Sprintf("FormFile: %v", err))
+		return
+	}
+	defer file.Close()
+
+	buf := make([]byte, 1024)
+	n, _ := file.Read(buf)
+	if n > 0 {
+		buf = buf[:n]
+	}
+	fileType := http.DetectContentType(buf)
+
+	if len(setting.Repository.Upload.AllowedTypes) > 0 {
+		allowed := false
+		for _, t := range setting.Repository.Upload.AllowedTypes {
+			t := strings.Trim(t, " ")
+			if t == "*/*" || t == fileType {
+				allowed = true
+				break
+			}
+		}
+
+		if !allowed {
+			ctx.Error(400, ErrFileTypeForbidden.Error())
+			return
+		}
+	}
+
+	upload, err := models.NewUpload(header.Filename, buf, file)
+	if err != nil {
+		ctx.Error(500, fmt.Sprintf("NewUpload: %v", err))
+		return
+	}
+
+	log.Trace("New file uploaded: %s", upload.UUID)
+	ctx.JSON(200, map[string]string{
+		"uuid": upload.UUID,
+	})
+}
+
+func RemoveUploadFileFromServer(ctx *context.Context, form auth.RemoveUploadFileForm) {
+	if len(form.File) == 0 {
+		ctx.Status(204)
+		return
+	}
+
+	if err := models.DeleteUploadByUUID(form.File); err != nil {
+		ctx.Error(500, fmt.Sprintf("DeleteUploadByUUID: %v", err))
+		return
+	}
+
+	log.Trace("Upload file removed: %s", form.File)
+	ctx.Status(204)
+}
diff --git a/routers/repo/issue.go b/routers/repo/issue.go
index a5908c182f..e2d8000e52 100644
--- a/routers/repo/issue.go
+++ b/routers/repo/issue.go
@@ -447,7 +447,6 @@ func UploadIssueAttachment(ctx *context.Context) {
 		return
 	}
 
-	allowedTypes := strings.Split(setting.AttachmentAllowedTypes, ",")
 	file, header, err := ctx.Req.FormFile("file")
 	if err != nil {
 		ctx.Error(500, fmt.Sprintf("FormFile: %v", err))
@@ -462,6 +461,7 @@ func UploadIssueAttachment(ctx *context.Context) {
 	}
 	fileType := http.DetectContentType(buf)
 
+	allowedTypes := strings.Split(setting.AttachmentAllowedTypes, ",")
 	allowed := false
 	for _, t := range allowedTypes {
 		t := strings.Trim(t, " ")
diff --git a/routers/repo/upload.go b/routers/repo/upload.go
deleted file mode 100644
index 5e0f91668f..0000000000
--- a/routers/repo/upload.go
+++ /dev/null
@@ -1,253 +0,0 @@
-// Copyright 2016 The Gogs Authors. All rights reserved.
-// Use of this source code is governed by a MIT-style
-// license that can be found in the LICENSE file.
-
-package repo
-
-import (
-	"fmt"
-	"net/http"
-	"path"
-	"strings"
-
-	git "github.com/gogits/git-module"
-
-	"github.com/gogits/gogs/models"
-	"github.com/gogits/gogs/modules/auth"
-	"github.com/gogits/gogs/modules/base"
-	"github.com/gogits/gogs/modules/context"
-	"github.com/gogits/gogs/modules/log"
-	"github.com/gogits/gogs/modules/setting"
-)
-
-const (
-	UPLOAD base.TplName = "repo/upload"
-)
-
-func renderUploadSettings(ctx *context.Context) {
-	ctx.Data["RequireDropzone"] = true
-	ctx.Data["IsUploadEnabled"] = setting.Repository.Upload.Enabled
-	ctx.Data["UploadAllowedTypes"] = strings.Join(setting.Repository.Upload.AllowedTypes, ",")
-	ctx.Data["UploadMaxSize"] = setting.Repository.Upload.FileMaxSize
-	ctx.Data["UploadMaxFiles"] = setting.Repository.Upload.MaxFiles
-}
-
-func UploadFile(ctx *context.Context) {
-	ctx.Data["PageIsUpload"] = true
-
-	userName := ctx.Repo.Owner.Name
-	repoName := ctx.Repo.Repository.Name
-	branchName := ctx.Repo.BranchName
-	branchLink := ctx.Repo.RepoLink + "/src/" + branchName
-	treeName := ctx.Repo.TreePath
-
-	treeNames := []string{""}
-	if len(treeName) > 0 {
-		treeNames = strings.Split(treeName, "/")
-	}
-
-	ctx.Data["UserName"] = userName
-	ctx.Data["RepoName"] = repoName
-	ctx.Data["BranchName"] = branchName
-	ctx.Data["TreeName"] = treeName
-	ctx.Data["TreeNames"] = treeNames
-	ctx.Data["BranchLink"] = branchLink
-	ctx.Data["CommitSummary"] = ""
-	ctx.Data["CommitMessage"] = ""
-	ctx.Data["CommitChoice"] = "direct"
-	ctx.Data["NewBranchName"] = ""
-	ctx.Data["CommitDirectlyToThisBranch"] = ctx.Tr("repo.commit_directly_to_this_branch", "<strong class=\"branch-name\">"+branchName+"</strong>")
-	ctx.Data["CreateNewBranch"] = ctx.Tr("repo.create_new_branch", "<strong>"+ctx.Tr("repo.new_branch")+"</strong>")
-	renderUploadSettings(ctx)
-
-	ctx.HTML(200, UPLOAD)
-}
-
-func UploadFilePost(ctx *context.Context, form auth.UploadRepoFileForm) {
-	ctx.Data["PageIsUpload"] = true
-	renderUploadSettings(ctx)
-
-	userName := ctx.Repo.Owner.Name
-	repoName := ctx.Repo.Repository.Name
-	oldBranchName := ctx.Repo.BranchName
-	branchName := oldBranchName
-	branchLink := ctx.Repo.RepoLink + "/src/" + branchName
-	commitChoice := form.CommitChoice
-	files := form.Files
-
-	if commitChoice == "commit-to-new-branch" {
-		branchName = form.NewBranchName
-	}
-
-	treeName := form.TreeName
-	treeName = strings.Trim(treeName, " ")
-	treeName = strings.Trim(treeName, "/")
-
-	treeNames := []string{""}
-	if len(treeName) > 0 {
-		treeNames = strings.Split(treeName, "/")
-	}
-
-	ctx.Data["UserName"] = userName
-	ctx.Data["RepoName"] = repoName
-	ctx.Data["BranchName"] = branchName
-	ctx.Data["TreeName"] = treeName
-	ctx.Data["TreeNames"] = treeNames
-	ctx.Data["BranchLink"] = branchLink
-	ctx.Data["CommitSummary"] = form.CommitSummary
-	ctx.Data["CommitMessage"] = form.CommitMessage
-	ctx.Data["CommitChoice"] = commitChoice
-	ctx.Data["NewBranchName"] = branchName
-	ctx.Data["CommitDirectlyToThisBranch"] = ctx.Tr("repo.commit_directly_to_this_branch", "<strong class=\"branch-name\">"+oldBranchName+"</strong>")
-	ctx.Data["CreateNewBranch"] = ctx.Tr("repo.create_new_branch", "<strong>"+ctx.Tr("repo.new_branch")+"</strong>")
-
-	if ctx.HasError() {
-		ctx.HTML(200, UPLOAD)
-		return
-	}
-
-	if oldBranchName != branchName {
-		if _, err := ctx.Repo.Repository.GetBranch(branchName); err == nil {
-			ctx.Data["Err_Branchname"] = true
-			ctx.RenderWithErr(ctx.Tr("repo.branch_already_exists"), UPLOAD, &form)
-			log.Error(4, "%s: %s - %s", "BranchName", branchName, "Branch already exists")
-			return
-		}
-
-	}
-
-	treepath := ""
-	for _, part := range treeNames {
-		treepath = path.Join(treepath, part)
-		entry, err := ctx.Repo.Commit.GetTreeEntryByPath(treepath)
-		if err != nil {
-			// Means there is no item with that name, so we're good
-			break
-		}
-		if !entry.IsDir() {
-			ctx.Data["Err_Filename"] = true
-			ctx.RenderWithErr(ctx.Tr("repo.directory_is_a_file"), UPLOAD, &form)
-			log.Error(4, "%s: %s - %s", "UploadFile", treeName, "Directory given is a file")
-			return
-		}
-	}
-
-	message := ""
-	if form.CommitSummary != "" {
-		message = strings.Trim(form.CommitSummary, " ")
-	} else {
-		message = ctx.Tr("repo.add_files_to_dir", "'"+treeName+"'")
-	}
-	if strings.Trim(form.CommitMessage, " ") != "" {
-		message += "\n\n" + strings.Trim(form.CommitMessage, " ")
-	}
-
-	if err := ctx.Repo.Repository.UploadRepoFiles(ctx.User, oldBranchName, branchName, treeName, message, files); err != nil {
-		ctx.Data["Err_Directory"] = true
-		ctx.RenderWithErr(ctx.Tr("repo.unable_to_upload_files"), UPLOAD, &form)
-		log.Error(4, "%s: %v", "UploadFile", err)
-		return
-	}
-
-	// Was successful, so now need to call models.CommitRepoAction() with the new commitID for webhooks and watchers
-	if branch, err := ctx.Repo.Repository.GetBranch(branchName); err != nil {
-		log.Error(4, "repo.Repository.GetBranch(%s): %v", branchName, err)
-	} else if commit, err := branch.GetCommit(); err != nil {
-		log.Error(4, "branch.GetCommit(): %v", err)
-	} else {
-		pc := &models.PushCommits{
-			Len:     1,
-			Commits: []*models.PushCommit{models.CommitToPushCommit(commit)},
-		}
-		oldCommitID := ctx.Repo.CommitID
-		newCommitID := commit.ID.String()
-		if branchName != oldBranchName {
-			oldCommitID = "0000000000000000000000000000000000000000" // New Branch so we use all 0s
-		}
-		if err := models.CommitRepoAction(models.CommitRepoActionOptions{
-			PusherName:  ctx.User.Name,
-			RepoOwnerID: ctx.Repo.Owner.ID,
-			RepoName:    ctx.Repo.Owner.Name,
-			RefFullName: git.BRANCH_PREFIX + branchName,
-			OldCommitID: oldCommitID,
-			NewCommitID: newCommitID,
-			Commits:     pc,
-		}); err != nil {
-			log.Error(4, "models.CommitRepoAction(branch = %s): %v", branchName, err)
-		}
-	}
-
-	ctx.Redirect(ctx.Repo.RepoLink + "/src/" + branchName + "/" + treeName)
-}
-
-func UploadFileToServer(ctx *context.Context) {
-	if !setting.Repository.Upload.Enabled {
-		ctx.Error(404, "upload is not enabled")
-		return
-	}
-
-	file, header, err := ctx.Req.FormFile("file")
-	if err != nil {
-		ctx.Error(500, fmt.Sprintf("FormFile: %v", err))
-		return
-	}
-	defer file.Close()
-
-	buf := make([]byte, 1024)
-	n, _ := file.Read(buf)
-	if n > 0 {
-		buf = buf[:n]
-	}
-	fileType := http.DetectContentType(buf)
-
-	if len(setting.Repository.Upload.AllowedTypes) > 0 {
-		allowed := false
-		for _, t := range setting.Repository.Upload.AllowedTypes {
-			t := strings.Trim(t, " ")
-			if t == "*/*" || t == fileType {
-				allowed = true
-				break
-			}
-		}
-
-		if !allowed {
-			ctx.Error(400, ErrFileTypeForbidden.Error())
-			return
-		}
-	}
-
-	up, err := models.NewUpload(header.Filename, buf, file, ctx.User.ID, ctx.Repo.Repository.ID)
-	if err != nil {
-		ctx.Error(500, fmt.Sprintf("NewUpload: %v", err))
-		return
-	}
-
-	log.Trace("New file uploaded: %s", up.UUID)
-	ctx.JSON(200, map[string]string{
-		"uuid": up.UUID,
-	})
-}
-
-func RemoveUploadFileFromServer(ctx *context.Context, form auth.RemoveUploadFileForm) {
-	if !setting.Repository.Upload.Enabled {
-		ctx.Error(404, "upload is not enabled")
-		return
-	}
-
-	if len(form.File) == 0 {
-		ctx.Error(404, "invalid params")
-		return
-	}
-
-	uuid := form.File
-
-	if err := models.RemoveUpload(uuid, ctx.User.ID, ctx.Repo.Repository.ID); err != nil {
-		ctx.Error(500, fmt.Sprintf("RemoveUpload: %v", err))
-		return
-	}
-
-	log.Trace("Upload file removed: %s", uuid)
-	ctx.JSON(200, map[string]string{
-		"uuid": uuid,
-	})
-}
diff --git a/routers/repo/view.go b/routers/repo/view.go
index 42bf62c606..055785564d 100644
--- a/routers/repo/view.go
+++ b/routers/repo/view.go
@@ -113,10 +113,7 @@ func renderDirectory(ctx *context.Context, treeLink string) {
 	// Check permission to add or upload new file.
 	if ctx.Repo.IsWriter() && ctx.Repo.IsViewBranch {
 		ctx.Data["CanAddFile"] = true
-		// uploadFileLink := ctx.Repo.RepoLink + "/upload/" + branchName
-		// if setting.Repository.Upload.Enabled {
-		// 	ctx.Data["UploadFileLink"] = uploadFileLink + "/" +  ctx.Repo.TreePath
-		// }
+		ctx.Data["CanUploadFile"] = setting.Repository.Upload.Enabled
 	}
 }
 
@@ -253,7 +250,7 @@ func Home(ctx *context.Context) {
 
 	ec, err := ctx.Repo.GetEditorconfig()
 	if err != nil && !git.IsErrNotExist(err) {
-		ctx.Handle(500, "ErrGettingEditorconfig", err)
+		ctx.Handle(500, "Repo.GetEditorconfig", err)
 		return
 	}
 	ctx.Data["Editorconfig"] = ec
diff --git a/templates/.VERSION b/templates/.VERSION
index bbf71e4218..68c6d095c7 100644
--- a/templates/.VERSION
+++ b/templates/.VERSION
@@ -1 +1 @@
-0.9.94.0830
\ No newline at end of file
+0.9.95.0830
\ No newline at end of file
diff --git a/templates/repo/editor/commit_form.tmpl b/templates/repo/editor/commit_form.tmpl
index 74126ac018..d76f3fb1c2 100644
--- a/templates/repo/editor/commit_form.tmpl
+++ b/templates/repo/editor/commit_form.tmpl
@@ -3,7 +3,7 @@
 	<div class="commit-form">
 		<h3>{{.i18n.Tr "repo.editor.commit_changes"}}</h3>
 		<div class="field">
-			<input name="commit_summary" placeholder="{{if .PageIsDelete}}{{.i18n.Tr "repo.editor.delete" .TreePath}}{{else if .IsNewFile}}{{.i18n.Tr "repo.editor.add_tmpl" .TreePath}}{{else}}{{.i18n.Tr "repo.editor.update" .TreePath}}{{end}}" value="{{.commit_summary}}" autofocus>
+			<input name="commit_summary" placeholder="{{if .PageIsDelete}}{{.i18n.Tr "repo.editor.delete" .TreePath}}{{else if .PageIsUpload}}{{.i18n.Tr "repo.editor.upload_files_to_dir" .TreePath}}{{else if .IsNewFile}}{{.i18n.Tr "repo.editor.add_tmpl" .TreePath}}{{else}}{{.i18n.Tr "repo.editor.update" .TreePath}}{{end}}" value="{{.commit_summary}}" autofocus>
 		</div>
 		<div class="field">
 			<textarea name="commit_message" placeholder="{{.i18n.Tr "repo.editor.commit_message_desc"}}" rows="5">{{.commit_message}}</textarea>
diff --git a/templates/repo/editor/upload.tmpl b/templates/repo/editor/upload.tmpl
new file mode 100644
index 0000000000..e1192ef026
--- /dev/null
+++ b/templates/repo/editor/upload.tmpl
@@ -0,0 +1,36 @@
+{{template "base/head" .}}
+<div class="repository file editor upload">
+	{{template "repo/header" .}}
+	<div class="ui container">
+		{{template "base/alert" .}}
+		<form class="ui comment form" method="post">
+			{{.CsrfTokenHtml}}
+			<div class="ui secondary menu">
+				<div class="item fitted treepath">
+					<div class="ui breadcrumb field {{if .Err_TreePath}}error{{end}}">
+						<a class="section" href="{{EscapePound $.BranchLink}}">{{.Repository.Name}}</a>
+						{{ $n := len .TreeNames}}
+						{{ $l := Subtract $n 1}}
+						{{range $i, $v := .TreeNames}}
+							<div class="divider"> / </div>
+							{{if eq $i $l}}
+								<input type="text" id="file-name" value="{{$v}}" placeholder="{{$.i18n.Tr "repo.editor.add_subdir"}}" autofocus>
+								<span class="octicon octicon-info poping up" data-content="{{$.i18n.Tr "repo.editor.filename_help"}}" data-position="bottom center" data-variation="tiny inverted"></span>
+							{{else}}
+								<span class="section"><a href="{{EscapePound $.BranchLink}}/{{EscapePound $v}}">{{$v}}</a></span>
+							{{end}}
+						{{end}}
+						<span>{{.i18n.Tr "repo.editor.or"}} <a href="{{EscapePound $.BranchLink}}{{if not .IsNewFile}}/{{EscapePound .TreePath}}{{end}}">{{.i18n.Tr "repo.editor.cancel_lower"}}</a></span>
+						<input type="hidden" id="tree_path" name="tree_path" value="{{.TreePath}}" required>
+					</div>
+				</div>
+			</div>
+			<div class="field">
+				<div class="files"></div>
+				<div class="ui basic button dropzone" id="dropzone" data-upload-url="{{.RepoLink}}/upload-file" data-remove-url="{{.RepoLink}}/upload-remove" data-csrf="{{.CsrfToken}}" data-accepts="{{.UploadAllowedTypes}}" data-max-file="{{.UploadMaxFiles}}" data-max-size="{{.UploadMaxSize}}" data-default-message="{{.i18n.Tr "dropzone.default_message"}}" data-invalid-input-type="{{.i18n.Tr "dropzone.invalid_input_type"}}" data-file-too-big="{{.i18n.Tr "dropzone.file_too_big"}}" data-remove-file="{{.i18n.Tr "dropzone.remove_file"}}"></div>
+			</div>
+			{{template "repo/editor/commit_form" .}}
+		</form>
+	</div>
+</div>
+{{template "base/footer" .}}
diff --git a/templates/repo/home.tmpl b/templates/repo/home.tmpl
index 2b8c7e06e0..c0c06a1438 100644
--- a/templates/repo/home.tmpl
+++ b/templates/repo/home.tmpl
@@ -18,36 +18,36 @@
 			{{template "repo/branch_dropdown" .}}
 			<div class="fitted item">
 				<div class="ui breadcrumb">
-					<a class="section" href="{{.RepoLink}}/src/{{EscapePound .BranchName}}">{{.Repository.Name}}</a>
+					<a class="section" href="{{.RepoLink}}/src/{{EscapePound .BranchName}}">{{EllipsisString .Repository.Name 25}}</a>
 					{{ $n := len .TreeNames}}
 					{{ $l := Subtract $n 1}}
 					{{range $i, $v := .TreeNames}}
 						<div class="divider"> / </div>
 						{{if eq $i $l}}
-							<span class="active section">{{$v}}</span>
+							<span class="active section">{{EllipsisString $v 15}}</span>
 						{{else}}
 							{{ $p := index $.Paths $i}}
-							<span class="section"><a href="{{EscapePound $.BranchLink}}/{{EscapePound $p}}">{{$v}}</a></span>
+							<span class="section"><a href="{{EscapePound $.BranchLink}}/{{EscapePound $p}}">{{EllipsisString $v 15}}</a></span>
 						{{end}}
 					{{end}}
 				</div>
 			</div>
 			<div class="right fitted item">
 				{{if .Repository.CanEnableEditor}}
-					<div id="file-buttons" class="ui tiny buttons">
+					<div id="file-buttons" class="ui tiny blue buttons">
 						{{if .CanAddFile}}
 							<a href="{{.RepoLink}}/_new/{{EscapePound .BranchName}}/{{EscapePound .TreePath}}" class="ui button">
 								{{.i18n.Tr "repo.editor.new_file"}}
 							</a>
 						{{end}}
-						{{if .UploadFileLink}}
-							<!-- <a href="{{EscapePound .UploadFileLink}}" class="ui button nowrap">
-								<i class="upload icon"></i> {{.i18n.Tr "repo.upload_file"}}
-							</a> -->
+						{{if .CanUploadFile}}
+							<a href="{{.RepoLink}}/_upload/{{EscapePound .BranchName}}/{{EscapePound .TreePath}}" class="ui button">
+								{{.i18n.Tr "repo.editor.upload_file"}}
+							</a>
 						{{end}}
 					</div>
 				{{end}}
-				
+
 				<!-- Only show colne panel in repository home page -->
 				{{if eq $n 0}}
 					<div class="ui action small input" id="clone-panel">
diff --git a/templates/repo/upload.tmpl b/templates/repo/upload.tmpl
deleted file mode 100644
index 9253b5cc9e..0000000000
--- a/templates/repo/upload.tmpl
+++ /dev/null
@@ -1,79 +0,0 @@
-{{template "base/head" .}}
-<div class="repository file upload">
-	{{template "repo/header" .}}
-	<div class="ui container">
-		{{.branchName}}
-		{{template "base/alert" .}}
-		<form class="ui comment form" action="{{EscapePound $.Link}}" method="post">
-			{{.CsrfTokenHtml}}
-			<div class="ui secondary menu">
-				<div class="item fitted" style="width:100%;">
-					<div class="ui breadcrumb field{{if .Err_Directory}} error{{end}}">
-						<a class="section" href="{{EscapePound $.BranchLink}}">{{.Repository.Name}}</a>
-						{{ $n := len .TreeNames}}
-						{{ $l := Subtract $n 1}}
-						{{range $i, $v := .TreeNames}}
-							<div class="divider"> / </div>
-							{{if eq $i $l}}
-								<input type="text" id="file-name" value="{{$v}}" placeholder="{{$.i18n.Tr "repo.add_subdir"}}">
-							{{else}}
-								<span class="section"><a href="{{EscapePound $.BranchLink}}/{{EscapePound $v}}">{{$v}}</a></span>
-							{{end}}
-						{{end}}
-						<button class="clipboard-tree-name icon octicon octicon-clippy poping up" type="button" data-content="{{.i18n.Tr "repo.copy_file_path_to_clipboard"}}" data-position="bottom center" data-variation="tiny inverted"></button>
-						<span class="repo-edit-file-cancel">{{.i18n.Tr "repo.or"}} <a href="{{EscapePound $.BranchLink}}/{{EscapePound $.TreeName}}">{{.i18n.Tr "repo.cancel_lower"}}</a></span>
-						<input type="hidden" id="tree-name" name="tree_name" value="{{.TreeName}}">
-					</div>
-				</div>
-			</div>
-			<div class="field ui upload">
-				<div class="files"></div>
-				<div class="ui basic button dropzone" id="dropzone" data-upload-url="{{.RepoLink}}/upload-file" data-remove-url="{{.RepoLink}}/upload-remove" data-csrf="{{.CsrfToken}}" data-accepts="{{.UploadAllowedTypes}}" data-max-file="{{.UploadMaxFiles}}" data-max-size="{{.UploadMaxSize}}" data-default-message="{{.i18n.Tr "dropzone.default_message"}}" data-invalid-input-type="{{.i18n.Tr "dropzone.invalid_input_type"}}" data-file-too-big="{{.i18n.Tr "dropzone.file_too_big"}}" data-remove-file="{{.i18n.Tr "dropzone.remove_file"}}"></div>
-			</div>
-			<div class="commit-form-wrapper">
-				<img width="48" height="48" class="ui rounded image commit-form-avatar" src="{{.SignedUser.AvatarLink}}">
-				<div class="commit-form">
-					<h3>{{.i18n.Tr "repo.commit_changes"}}</h3>
-					<div class="field">
-						<input name="commit_summary" placeholder="{{.i18n.Tr "repo.add_files_to_dir" .TreeName}}" value="{{.CommitSummary}}">
-					</div>
-					<div class="field">
-						<textarea name="commit_message" placeholder="{{.i18n.Tr "repo.default_commit_message"}}">{{.CommitMessage}}</textarea>
-					</div>
-					<div class="quick-pull-choice js-quick-pull-choice ">
-						<dl class="form-group">
-							<dd>
-						 		<div class="form-checkbox">
-									<label>
-										<input type="radio" class="js-quick-pull-choice-option" name="commit_choice" value="direct"{{if eq .CommitChoice "direct"}} checked="checked"{{end}}>
-										<i class="octicon octicon-git-commit" height="16" width="14"></i>
-										{{.CommitDirectlyToThisBranch | Safe}}
-									</label>
-								</div>
-								<div class="form-checkbox">
-									<label>
-										<input type="radio" class="js-quick-pull-choice-option" name="commit_choice" value="commit-to-new-branch"{{if eq .CommitChoice "commit-to-new-branch"}} checked="checked"{{end}}>
-										<i class="octicon octicon-git-pull-request" height="16" width="12"></i>
-										{{.CreateNewBranch | Safe}}
-									</label>
-								</div>
-							</dd>
-						</dl>
-						<div class="quick-pull-branch-name">
-							<div class="new-branch-name-input{{if .Err_Branchname}} error{{end}}">
-								<i class="octicon octicon-git-branch quick-pull-new-branch-icon" height="16" width="10"></i>
-								<input type="text" name="new_branch_name" value="{{.NewBranchName}}" class="form-control input-contrast mr-2 js-quick-pull-new-branch-name" placeholder="New branch nameā€¦">
-								<span class="text-muted js-quick-pull-normalization-info"></span>
-							</div>
-						</div>
-					</div>
-				</div>
-				<button type="submit" class="ui green button">
-					{{.i18n.Tr "repo.commit_changes"}}
-				</button>
-				<a class="ui button red" href="{{EscapePound $.BranchLink}}/{{EscapePound $.TreeName}}">{{.i18n.Tr "repo.cancel"}}</a>
-			</div>
-		</form>
-	</div>
-</div>
-{{template "base/footer" .}}