gpt4 book ai didi

grails - 文件仅上传具有枚举的图像的指定内容类型

转载 作者:行者123 更新时间:2023-12-02 14:15:32 25 4
gpt4 key购买 nike

我正在为Grails使用HDImageService插件来繁琐地缩放用户上传的图像。我创建了ImageService.groovy以保存到我的Amazon S3存储桶。一切正常,用户选择文件,单击发布,然后缩放,存储和显示图像。我的问题是我不知道如何限制用户上传图像以外的文件。我只允许上传jpeg,jpg,gif或png类型的文件。我已经用这些变量创建了一个ENUM类,但是我不知道在哪里或如何实现。谁能指出我正确的方向

RegistrationController.groovy:获取文件并保存到存储桶

         if ( params.photo ) {
MultipartFile file = request.getFile( 'photo' )
byte[] fileBytes = file.bytes
ByteArrayInputStream bais = new ByteArrayInputStream( fileBytes )
BufferedImage image = ImageIO.read( bais )
def width = image.width
def height = image.height
def maxWidth = 500

// Calculate the ratio that we will need to resize the image
double ratio = 1.0f
if ( width > maxWidth ) {
def r = maxWidth / width
ratio = r < 1.0f ? r : 1.0f
bais.reset()
fileBytes = hdImageService.scale( bais, maxWidth, Math.round( height * ratio ) as int )
}

geolink.custPhoto = imageService.storeS3Image(
imageService.buildPPJPhotoPath( geolink, file.getOriginalFilename() ),
fileBytes,
file.contentType
)
}

ImageService.groovy:枚举
    String getFormatName( byte[] raw ) {
try {
// Create an image input stream on the image
ImageInputStream iis = ImageIO.createImageInputStream( new ByteArrayInputStream( raw ) )

// Find all image readers that recognize the image format
Iterator iter = ImageIO.getImageReaders(iis)
if (!iter.hasNext()) {
// No readers found
log.debug( "Unable to get format" )
return null;
}

// Use the first reader
ImageReader reader = (ImageReader)iter.next()

// Close stream
iis.close()

// Return the format name
log.debug( "Format: ${reader.getFormatName() }" )
return reader.getFormatName()
}
catch (IOException e) {
log.warn( "Unable to determine image format", e )
}
// The image could not be read
return null;
}

ImageFormat getContentType( String filename ) {
String[] parts = filename.split( '\\.' )
return ImageFormat.valueOf( parts[parts.length - 1].toUpperCase() )
}}

public enum ImageFormat {
JPEG( 'image/jpeg', 'jpg' ),
JPG( 'image/jpeg', 'jpg' ),
PNG( 'image/png', 'png' ),
GIF( 'image/gif', 'gif' )

String mimeType
String extension

public ImageFormat( String mime, String ext ) {
this.mimeType = mime
this.extension = ext
}

}

最佳答案

这是我的方法。将其修改为枚举应该很容易:

def downloadedFile = request.getFile('imageFile')
def okContentTypes = ['image/png', 'image/jpeg', 'image/jpg', 'image/gif']

if (!okContentTypes.contains(downloadedFile.getContentType())) {
myDomainInstance.errors.rejectValue("image", "Image type must be one of: ${okContentTypes}")
}

关于grails - 文件仅上传具有枚举的图像的指定内容类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13386922/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com