这里需要用到图片编辑工具Thumbnails,文章中附有jar
前端代码
#{set title:'Home' /}
<div style="margin: 0px auto;">
<h1>下载图片并在后台缩小后返回原图与缩小图到展示页面</h1>
<form action="/Application/imgLocation" method="post"
enctype="multipart/form-data">
<input type="file" name="file" /> <input type="submit" value="上传" />
</form>
</div>
后台接收图片
package controllers;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import net.coobird.thumbnailator.Thumbnails;
import play.Play;
import play.data.Upload;
import play.mvc.Controller;
import com.google.common.io.Files;
public class Application extends Controller {
public static void index() {
render();
}
public static void uploadPage(){
render();
}
public static void imgLocation(File file) throws IOException {
String maxUrl = "public/images/raw"+file.getName();
String minUrl = "public/images/shrink"+file.getName();
//原图片保存在项目中
Files.copy(file, Play.getFile("public/images/raw"+file.getName()));
//缩小图片保存在项目中
Thumbnails.of( new FileInputStream(file)).size(100,100).toFile(minUrl);;
renderArgs.put("maxImage","http://localhost:1234/"+ maxUrl);
renderArgs.put("minImage","http://localhost:1234/"+ minUrl);
render();
}
}
配置链接路由
# Home page
GET /Application/index Application.index
#upload page
GET /Application/uploadPage Application.uploadPage
#show page
POST /Application/imgLocation Application.imgLocation
展示页面代码
#{set title:'Home' /}
<style type="text/css">
#max,#min{
float:left;
}
</style>
<div style="margin: 0px auto;">
<div id="max"><input type="image" src="${maxImage}" /></div>
<div id="min"><input type="image" src="${minImage}" /></div>
</div>