Skip to content
GitLab
Explore
Sign in
Primary navigation
Search or go to…
Project
B
Backend
Manage
Activity
Members
Labels
Plan
Issues
Issue boards
Milestones
Wiki
Code
Merge requests
Repository
Branches
Commits
Tags
Repository graph
Compare revisions
Snippets
Build
Pipelines
Jobs
Pipeline schedules
Artifacts
Deploy
Releases
Package registry
Model registry
Operate
Environments
Terraform modules
Monitor
Incidents
Analyze
Value stream analytics
Contributor analytics
CI/CD analytics
Repository analytics
Model experiments
Help
Help
Support
GitLab documentation
Compare GitLab plans
Community forum
Contribute to GitLab
Provide feedback
Keyboard shortcuts
?
Snippets
Groups
Projects
Show more breadcrumbs
IDATT2106 Scrum Team 02
Backend
Merge requests
!26
Implementer filhåndtering for profilbilder
Code
Review changes
Check out branch
Download
Patches
Plain diff
Merged
Implementer filhåndtering for profilbilder
profilbilder
into
main
Overview
0
Commits
1
Pipelines
1
Changes
3
Merged
Jakob Karevold Grønhaug
requested to merge
profilbilder
into
main
2 years ago
Overview
0
Commits
1
Pipelines
1
Changes
3
Expand
0
0
Merge request reports
Compare
main
main (base)
and
latest version
latest version
27a830d2
1 commit,
2 years ago
3 files
+
160
−
3
Side-by-side
Compare changes
Side-by-side
Inline
Show whitespace changes
Show one file at a time
Files
3
Search (e.g. *.vue) (Ctrl+P)
src/main/java/edu/ntnu/idatt210602/matsvinnbackend/controller/FileController.java
0 → 100644
+
154
−
0
Options
package
edu.ntnu.idatt210602.matsvinnbackend.controller
;
import
java.io.IOException
;
import
java.nio.file.Files
;
import
java.nio.file.Paths
;
import
java.nio.file.StandardCopyOption
;
import
org.springframework.beans.factory.annotation.Autowired
;
import
org.springframework.beans.factory.annotation.Value
;
import
org.springframework.core.io.Resource
;
import
org.springframework.core.io.UrlResource
;
import
org.springframework.http.HttpHeaders
;
import
org.springframework.http.HttpStatus
;
import
org.springframework.http.MediaType
;
import
org.springframework.http.ResponseEntity
;
import
org.springframework.security.core.context.SecurityContextHolder
;
import
org.springframework.stereotype.Controller
;
import
org.springframework.web.bind.annotation.DeleteMapping
;
import
org.springframework.web.bind.annotation.GetMapping
;
import
org.springframework.web.bind.annotation.PathVariable
;
import
org.springframework.web.bind.annotation.PostMapping
;
import
org.springframework.web.bind.annotation.RequestMapping
;
import
org.springframework.web.bind.annotation.RequestParam
;
import
org.springframework.web.multipart.MultipartFile
;
import
org.springframework.web.server.ResponseStatusException
;
import
org.springframework.web.servlet.support.ServletUriComponentsBuilder
;
import
org.slf4j.Logger
;
import
org.slf4j.LoggerFactory
;
import
edu.ntnu.idatt210602.matsvinnbackend.model.Account
;
import
edu.ntnu.idatt210602.matsvinnbackend.model.Profile
;
import
edu.ntnu.idatt210602.matsvinnbackend.repo.AccountRepository
;
import
edu.ntnu.idatt210602.matsvinnbackend.repo.ProfileRepository
;
import
java.nio.file.Path
;
@Controller
@RequestMapping
(
path
=
"/img"
)
public
class
FileController
{
Logger
logger
=
LoggerFactory
.
getLogger
(
ProfileController
.
class
);
@Value
(
"${filebucket.path}"
)
String
basePath
;
@Autowired
AccountRepository
accountRepo
;
@Autowired
ProfileRepository
profileRepo
;
@PostMapping
(
""
)
public
ResponseEntity
<
String
>
uploadProfilePicture
(
@RequestParam
(
"file"
)
MultipartFile
file
,
@RequestParam
(
"profileId"
)
Integer
profileId
)
{
String
authenticatedUsername
=
SecurityContextHolder
.
getContext
().
getAuthentication
().
getName
();
Account
loggedInAccount
=
accountRepo
.
findByEmail
(
authenticatedUsername
).
orElseThrow
();
// Ensure that the provided profile ID is valid
Profile
profile
=
profileRepo
.
findById
(
profileId
).
orElseThrow
(()
->
{
return
new
ResponseStatusException
(
HttpStatus
.
BAD_REQUEST
);
});
// Ensure that the profile is part of the authenticated account
if
(!
loggedInAccount
.
getId
().
equals
(
profile
.
getAccountId
()))
{
throw
new
ResponseStatusException
(
HttpStatus
.
FORBIDDEN
);
}
// Allow only JPEG images
if
(!
file
.
getContentType
().
equals
(
MediaType
.
IMAGE_JPEG_VALUE
))
{
throw
new
ResponseStatusException
(
HttpStatus
.
UNSUPPORTED_MEDIA_TYPE
);
}
// Only allow images up to 512 kilobytes
if
(
file
.
getSize
()
>
524288
)
{
throw
new
ResponseStatusException
(
HttpStatus
.
PAYLOAD_TOO_LARGE
);
}
// Use unique profile ID as filename for 1:1 mapping between profiles and images
String
filename
=
String
.
format
(
"%d.jpeg"
,
profileId
);
Path
path
=
Paths
.
get
(
basePath
,
filename
);
try
{
Files
.
copy
(
file
.
getInputStream
(),
path
,
StandardCopyOption
.
REPLACE_EXISTING
);
}
catch
(
IOException
e
)
{
logger
.
error
(
"Unable to write uploaded file to storage!"
);
}
String
fileDownloadUri
=
ServletUriComponentsBuilder
.
fromCurrentContextPath
()
.
path
(
"/img/"
)
.
path
(
profileId
.
toString
())
.
toUriString
();
return
ResponseEntity
.
ok
(
fileDownloadUri
);
}
@GetMapping
(
"/{profileId:.+}"
)
public
ResponseEntity
<
Resource
>
get
(
@PathVariable
Integer
profileId
)
{
String
authenticatedUsername
=
SecurityContextHolder
.
getContext
().
getAuthentication
().
getName
();
Account
loggedInAccount
=
accountRepo
.
findByEmail
(
authenticatedUsername
).
orElseThrow
();
// Ensure that the provided profile ID is valid
Profile
profile
=
profileRepo
.
findById
(
profileId
).
orElseThrow
(()
->
{
return
new
ResponseStatusException
(
HttpStatus
.
BAD_REQUEST
);
});
// Ensure that the profile is part of the authenticated account
if
(!
loggedInAccount
.
getId
().
equals
(
profile
.
getAccountId
()))
{
throw
new
ResponseStatusException
(
HttpStatus
.
FORBIDDEN
);
}
Path
path
=
Paths
.
get
(
basePath
,
String
.
format
(
"%d.jpeg"
,
profileId
));
if
(!
path
.
toFile
().
exists
())
{
throw
new
ResponseStatusException
(
HttpStatus
.
NOT_FOUND
);
}
Resource
file
=
null
;
try
{
file
=
new
UrlResource
(
path
.
toUri
());
}
catch
(
Exception
e
)
{
throw
new
ResponseStatusException
(
HttpStatus
.
NOT_FOUND
);
}
return
ResponseEntity
.
ok
()
.
contentType
(
MediaType
.
IMAGE_JPEG
)
.
header
(
HttpHeaders
.
CONTENT_DISPOSITION
,
"attachment; filename=\""
+
file
.
getFilename
()
+
"\""
)
.
body
(
file
);
}
@DeleteMapping
(
""
)
public
ResponseEntity
<
Void
>
deleteImage
(
@RequestParam
(
"profileId"
)
Integer
profileId
)
{
String
authenticatedUsername
=
SecurityContextHolder
.
getContext
().
getAuthentication
().
getName
();
Account
loggedInAccount
=
accountRepo
.
findByEmail
(
authenticatedUsername
).
orElseThrow
();
// Ensure that the provided profile ID is valid
Profile
profile
=
profileRepo
.
findById
(
profileId
).
orElseThrow
(()
->
{
return
new
ResponseStatusException
(
HttpStatus
.
BAD_REQUEST
);
});
// Ensure that the profile is part of the authenticated account
if
(!
loggedInAccount
.
getId
().
equals
(
profile
.
getAccountId
()))
{
throw
new
ResponseStatusException
(
HttpStatus
.
FORBIDDEN
);
}
Path
path
=
Paths
.
get
(
basePath
,
String
.
format
(
"%d.jpeg"
,
profileId
));
if
(
path
.
toFile
().
delete
())
{
return
ResponseEntity
.
ok
().
build
();
}
else
{
throw
new
ResponseStatusException
(
HttpStatus
.
INTERNAL_SERVER_ERROR
);
}
}
}
\ No newline at end of file
Loading