EasyUI上传图片,前台预览,后台读取

背景

Spring MVC + EasyUI

前台上传图片,并预览

下面是jsp的内容,form表单

java 
<form id="upload_form" enctype="multipart/form-data" action="upload_deal.do" method="post">
        <input class="easyui-filebox" style="width:300px" data-options='onChange:change_photo' id="file_upload" name="file_upload2"/><br/> 
        <input type="submit" value="提交" /> <br/>
    </form>
    <div id="Imgdiv">
        <img id="Img" width="200px" height="200px"/>
    </div>

对应调用JS如下

java
function change_photo(){
        PreviewImage($("input[name='file_upload2']")[0], 'Img', 'Imgdiv');
    }

其中PreviewImage方法是借用网上大神的代码,这里写链接内容

后台

首先要在Spring-servlet.xml中添加与文件上传相关的配置,这里的100000是图片大小(byte)

java
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize" value="100000"/>
    </bean>

Action部分

java
@Controller
public class PictureTest {

    @Resource HibernateTemplate hibernateTemplate;

    @RequestMapping("/upload_deal")
    public ModelAndView upload_deal(
            @RequestParam(value="file_upload", required=false) MultipartFile file, 
            HttpServletRequest request, HttpServletResponse response) throws IOException{
        savePicture(file, request);//保存图片

        List<Picture> pics = (List<Picture>)hibernateTemplate.find("from Picture");
        ModelAndView mav = new ModelAndView();
        mav.addObject("photo", pics.get(0).getPhoto_path());
        mav.setViewName("/Test/showPicture");
        return mav;
    }


    //文件保存到服务器上
    protected void savePicture(MultipartFile file, HttpServletRequest request)
            throws IOException, FileNotFoundException {
        String ImagePath = request.getSession().getServletContext().getRealPath("/static/img");
        File targetfile = new File(ImagePath, file.getOriginalFilename());
        Date date = new Date(System.currentTimeMillis());
        if(targetfile.exists()){
            String[] s = file.getOriginalFilename().split("\\.");
            s[0] += date.getTime();
            targetfile = new File(ImagePath, s[0] + "." + s[1]);
        }
        InputStream ins = file.getInputStream();
        FileOutputStream fos = new FileOutputStream(targetfile);

        byte b[] = new byte[1024];
        int temp = 0;

        while((temp = ins.read(b)) != -1){
            fos.write(b, 0, temp);
        }

        fos.close();
        ins.close();
    }
}

注意这里的ModeAndView需要Import的包是org.springframework.web.servlet.ModelAndView;否则返回前台很有可能是404错误;

  • 3
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值