1

有用:

查看(普惠制):

<g:uploadForm action="upload">
    <input type="file" name="myImageFile" />
    <input type="submit" />
</g:uploadForm>

控制器:

def destination = "D:\\someFolder\\image.jpg";
def f = request.getFile('myImageFile')
f.transferTo(new File(destination))
response.sendError(200, 'Done')

我想始终将其转换为 JPG 图像。所以我尝试了:

def destination = "D:\\someFolder\\image.jpg";
PlanarImage inputfile = JAI.create("FileLoad", f);
JAI.create("filestore",inputfile,destination,"JPEG");

这是错误:

FileLoad - 参数值类 (org.springframework.web.multipart.commons.CommonsMultipartFile) 不是参数“文件名”的参数类 (java.lang.String) 的实例。堆栈跟踪如下:

到目前为止,我唯一的解决方案是在检查图像是否为图像后正常保存图像(感谢@james-kleeh)。然后用 JAI.create 加载它并做这些事情。最后删除原始图像。

我也想知道如何检查上传的文件是否为图像

4

2 回答 2

1

GSP 代码与我在问题中发布的代码相同。

控制器代码将是这样的:

import javax.media.jai.*;
...

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

if (!okContentTypes.contains(f.getContentType())) { 
    // TODO Tell user: "Image type must be one of: ${okContentTypes}"
}

else {
    def destination = "D:\\someFolder\\image.jpg";
    byte[] source = f.bytes;
    SeekableStream inputStream = new ByteArraySeekableStream(source);
    RenderedOp image = JAI.create("stream", inputStream)
    JAI.create("filestore",image,destination,"JPEG"); // Destination directory must exist (D:\someFolder\)
}

我希望它对某人有用!

于 2013-08-07T01:03:06.210 回答
0

遵循控制器端代码,我用来将上传的图像保存在应用程序之外。

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

if (!okContentTypes.contains(f.getContentType())) { 
    //TODO Tell user: "Image type must be one of: ${okContentTypes}"
} else {
    def destination = "/opt/jft/profileImages"  //path to dir where images will be saved. In my case profileImages is the destination dir.
    File dir = new File(destination)
    dir.mkdirs()
    f.transferTo(new File(dir, f.getOriginalFilename()))
}

在这里,您不需要现有的目标目录,如果它不存在,则程序将创建它。

于 2013-08-09T17:46:03.577 回答