任何人都可以帮我如何从grails中的url下载图像。目前我使用以下代码,但它保存在应用程序的当前文件夹中。我想下载浏览器特定的文件夹(比如从web或saveAS下载一些文件的默认文件夹)
def imageDownload() {
//imageURL = "http://www.google.com/images/logo.png"
String fullPath = params.imageURL
String baseName = FilenameUtils.getBaseName(fullPath);
String extension = FilenameUtils.getExtension(fullPath);
def fileName = baseName+"."+extension
def fileDoc = new File(fullPath);
def webUtils = WebUtils.retrieveGrailsWebRequest()
def response = webUtils.getCurrentResponse()
response.setContentType("application/png")
response.setHeader "Content-disposition", "attachment; filename=\"${fileName}\"";
def file = new FileOutputStream(fullPath.tokenize("/")[-1])
def out = new BufferedOutputStream(file)
out << new URL(fullPath).openStream()
out.close()
redirect(action: "imageDetails", params:params)
}
需要帮助,谢谢。
答案 0 :(得分:3)
def downloadImage = {
def fileURL = "http://www.google.com/images/logo.gif"
def thisUrl = new URL(fileURL);
def connection = thisUrl.openConnection();
def dataStream = connection.inputStream
response.setContentType("application/octet-stream")
response.setHeader('Content-disposition', 'Attachment; filename=logo.gif')
response.outputStream << dataStream
response.outputStream.flush()
}
答案 1 :(得分:0)
def download() {
String fullPath = params.imageURL
String baseName = FilenameUtils.getBaseName(fullPath);
String extension = FilenameUtils.getExtension(fullPath);
def fileName = baseName+"."+extension
def webUtils = WebUtils.retrieveGrailsWebRequest()
def response = webUtils.getCurrentResponse()
response.setContentType("application/png")
response.setHeader "Content-disposition", "attachment; filename=\"${fileName}\"";
def outputStream = response.getOutputStream()
URL url = new URL(fullPath);
InputStream is = new BufferedInputStream(url.openStream());
byte[] buffer = new byte[1024];
int length=0;
while (-1!=(length=is.read(buffer)))
{
outputStream.write(buffer, 0, length);
}
outputStream.close();
is.close();
}
这就是我正在使用的..它已成功下载...
答案 2 :(得分:0)
你可以通过一些巧妙的技巧轻松完成:
URL urlCont = new URL(imageURL);
InputStream inStream = new BufferedInputStream(urlCont.openStream());
byte[] bytes = IOUtils.toByteArray(inStream);