上传图片后缩小并保存到项目中


  • 这里需要用到图片编辑工具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>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值