图片上传(高级,带备份)

高级图片上传

该功能主要是防止服务器重新部署导致图片等一系列东西丢失,一下是实现的流程

下面不啰嗦开始上代码

效果图
开始上传前
这里写图片描述
这里写图片描述

jsp页面

<%@page import="com.education.project.util.CommonsUtil"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<c:set var="pageurl" value="${pageContext.request.contextPath}"></c:set>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet"
    href="${pageurl }/resources/jquery-file-upload/css/jquery.fileupload.css">
<script
    src="${pageurl }/resources/jquery/<%=CommonsUtil.JQUERY_VERSION %>/jquery.js"></script>
<script
    src="${pageurl }/resources/jquery-file-upload/js/vendor/jquery.ui.widget.js"></script>
<!-- 发送Ajax文件上传请求对返回JSON的处理 -->
<script
    src="${pageurl }/resources/jquery-file-upload/js/jquery.iframe-transport.js"></script>
<script
    src="${pageurl }/resources/jquery-file-upload/js/jquery.fileupload.js"></script>
<script
    src="${pageurl }/resources/js/file_upload.js"></script>
<title>Insert title here</title>
</head>
<body>
    <h4>使用fileupload上传图片</h4>
    <input type="hidden" id="pageurl" value="${pageurl }"/>
    <form id="imgform" action="${pageurl }/file/fileupload" method="post">
        <input type="hidden" name="imageurl"/>
        <div class="col-sm-6">
            <div class="fileinput-button">
                <img id="preimage" class="img-thumbnail" src="${pageurl }/resources/images/uploadphoto.jpg" width="120" height="160">
                <input type="file" name="file" id="fileupload" data-url="${pageurl }/file/upload">
            </div>
        </div>
        <br>
        <button type="button" id="uploadbtn">上传</button>
    </form>
    <h4>显示上传的图片</h4>
    <div>
        <img alt="暂无图片" id="localimg" src="${pageurl }/resources/images/nophoto.jpg" width="120" height="160">
    </div>
</body>
</html>

js文件

$(function() {
    var pageurl = $('#pageurl').val();
    var $preimage = $('#preimage');
    var $form = $('#imgform');
    //图片预览
    $('#fileupload').fileupload({
        dataType: 'json',
        done: function(e, data) {
            var res = data.result.files[0];
            if (res.success) {
                alert(res.url);
                $preimage.attr('src', pageurl + res.url);
                $form.find('input[name=imageurl]').val(res.url);
            } else {
                alert(res.message);
            }
        }
    });
    var imageurl = $form.find('input[name=imageurl]').val();
    if (typeof(imageurl) != 'undefined' && imageurl != null && imageurl != '') {
        $preimage.attr('src', pageurl + imageurl);
    }
    //
    $("#uploadbtn").click(function(){
        var imgrul=$("input[name=imageurl]").val();
        $.post(pageurl+"/file/fileupload",{"imageurl":imgrul},function(data){
            if (data.success) {
                alert("上传成功");
                alert(data.pathname);
                $("#localimg").attr("src",pageurl+"/file/read_local_images?image="+data.pathname);
            }
        },"json")
    })
})

Controller层

package com.education.project.web.controller;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.education.project.service.FileuploadService;
@Controller
@RequestMapping("/file")
public class FileUploadController {
    @Value("${project.locationPath}")
    private String locationPath;
    @Autowired
    private FileuploadService fileuploadService;
    @RequestMapping("/index")
    public String fileIndex(){
        return "/fileupload/index";
    }
    //读取本地图片
    @RequestMapping("read_local_images")
    public ModelAndView read_local_images(@RequestParam(value="image",defaultValue="nophoto.jpg")String image){
        ModelAndView model=new ModelAndView("readLocalImages");
        File img=new File(locationPath, "img");
        File data=new File(img, "20180611");
        File endFile=new File(data, image);
        model.addObject("file", endFile);
        return model;
    }
    //将图片上传到本地
    @RequestMapping("/fileupload")
    public @ResponseBody Map<String, Object> fileupload(HttpSession session,String imageurl) throws Exception{
        Map<String, Object> map=new HashMap<>();
        String pathname=session.getServletContext().getRealPath(imageurl);
        File file=new File(pathname);
        fileuploadService.fileupload(file); 
        map.put("success", true);
        map.put("pathname", imageurl.substring(5));
        return map;
    }
    //图片预览
    @RequestMapping(value="/upload",method=RequestMethod.POST)
    public @ResponseBody Map<String, Object> imguploadPrev(
            @RequestParam("file")MultipartFile file,
            HttpServletRequest request
            ) throws Exception, IOException{
        Map<String, Object> result=new HashMap<>();     
        List<Map<String, Object>> resFiles=new ArrayList<>();   
        //获取上传文件的名字
        String origionName=file.getOriginalFilename();

        //将文件名小写
        String suffix=origionName.toLowerCase();
        //判断是不是jpg/jpeg的图片
        if (suffix.endsWith("jpg")||suffix.endsWith("jpeg")) {
            //获取当前的路径
            File currentPath=new File(request.getSession().getServletContext().getRealPath("/prev"));

            String newFileName=UUID.randomUUID().toString()+".jpg";

            //将当前的图片保存
            File out=new File(currentPath, newFileName);
            file.transferTo(out);

            //设置返回的map
            Map<String, Object> res=new HashMap<>();
            //将图片从磁盘加载到内存中,方便对图片的操作
            BufferedImage image = ImageIO.read(out); 
            //判断图片是否真的存在
            if (image!=null) {
                if (image.getWidth()==0||image.getHeight()==0) {
                    res.put("success", false);
                    res.put("message", "请上传jpg格式照片");
                    resFiles.add(res);
                    out.delete();
                    result.put("files", resFiles);
                    return result;
                }
            }else{
                res.put("success", false);
                res.put("message", "请上传jpg格式照片");
                resFiles.add(res);
                out.delete();
                result.put("files", resFiles);
                return result;
            }
            res.put("success", true);
            res.put("name", newFileName);
            res.put("size", file.getSize());
            res.put("url", "/prev/"+newFileName);
            resFiles.add(res);
        }else{
            Map<String, Object> res = new HashMap<String, Object>();
            res.put("success", false);
            res.put("message", "请上传jpg格式照片");
            resFiles.add(res);
        }
        result.put("files", resFiles);
        return result;
    }

}

View.xml(需要在springmvc的配置文件中引入这个自定义视图)

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"  
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
    xmlns:p="http://www.springframework.org/schema/p"  
    xsi:schemaLocation="  
        http://www.springframework.org/schema/beans  
        http://www.springframework.org/schema/beans/spring-beans-4.3.xsd  "> 

    <bean id="kaptchaImageCodeView" class="com.education.project.web.view.KaptchaImageCodeView"
        p:captchaProducer-ref="captchaProducer"/>
    <bean id="readLocalImages" class="com.education.project.web.view.StudentImageView"/>

</beans>

读取本地文件的java类

package com.education.project.web.view;

import java.io.File;
import java.io.OutputStream;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.springframework.web.servlet.view.AbstractView;

public class StudentImageView extends AbstractView {

    @Override
    protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest req, HttpServletResponse resp)
            throws Exception {
           // return a jpeg
           resp.setContentType("image/jpeg");   
           File outFile = null;
           File file = (File) model.get("file");
           if(file.exists()){
               outFile = file;
           }else{
               outFile = new File(req.getSession().getServletContext().getRealPath("/resources/images/nophoto.jpg"));
           }
           OutputStream os = resp.getOutputStream();
           FileUtils.copyFile(outFile, os);
           os.flush();
           os.close();
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值