1. 程式人生 > >圖片或檔案上傳到伺服器或從伺服器上讀取(圖片可根據路徑src回顯展示,從伺服器上讀出來)

圖片或檔案上傳到伺服器或從伺服器上讀取(圖片可根據路徑src回顯展示,從伺服器上讀出來)

不需要配置虛擬路徑,存的時候資料庫裡只存了圖片的名稱(隨機重新命名的形式),存在指定伺服器上,取的時候也是根據圖片名稱從伺服器上找到,並用OutputStream 讀出來

前臺頁面(用的bootstrap):

html程式碼(可回顯,回顯的時候也是去後臺根據路徑查詢到圖片):

<form id="pic" method="post" enctype="multipart/form-data">
<input type="hidden" name="id" value="${userComplete.id}">
<div  class="row">
   <div class="col-xs-2">
      <label class="control-label">營業執照:</label>
   </div>
   <div class="col-xs-4 updateP1">
      <img src="${pageContext.request.contextPath}/corporation/showImages/${userComplete.businessLicense}" 
id="businessLicense" 
style="width: 150px;height: 150px; border:1px solid #989898;">
      <input type="hidden" name="businessLicense" value="${userComplete.businessLicense}"/>
   </div>
   <div class="col-md-4">
       <div class="container">
       <div class="col-md-12">
           <input type="file" name="file1" id="file1">
       </div>
       &nbsp;&nbsp;&nbsp;&nbsp;<input type="button" value="重新上傳" onclick="doUpload1()">
   </div>
   </div>
</div>
<div  class="row">
   <div class="col-xs-1 col-xs-offset-3">
       <input type="submit" name="提交" class="btn btn-danger">
   </div>
</div>
</form>

js:

<script>
    //圖片預覽路徑
    function getObjectURL(file) {
        var url = null;
        if(window.createObjectURL != undefined) { // basic
            url = window.createObjectURL(file);
        } else if(window.URL != undefined) { // mozilla(firefox)
            url = window.URL.createObjectURL(file);
        } else if(window.webkitURL != undefined) { // webkit or chrome
            url = window.webkitURL.createObjectURL(file);
        }
        return url;
    }
    function doUpload1(){
        var formd = new FormData($("#pic")[0]);
        var imgurl = getObjectURL($("#file1")[0].files[0]);
        $("#businessLicense").attr({
            "src":imgurl
        });
        var url="${pageContext.request.contextPath}/corporation/sendFile1";
        $.ajax({
            type:"post",
            url:url,
            data:formd,
            contentType:false,
            processData:false,
            dataType:"json",
            success:function (data) {
                if(null!=data && data.flag==true){
                    alert("上傳成功!");
                    $("#pic input[name='businessLicense']").val(data.filename);
                }
            },error:function (data) {
                alert(1);
                alert(data.message);
            }
        });
    }
$("#pic").submit(function () {
        var data = $("#pic").serialize();
        $.ajax({
            url:"${pageContext.request.contextPath}/corporation/updateCorporation",
            data:data,
            type:"post",
            datatype:"json",
            success:function (data) {
                if(data){
                    alert("修改成功!");
                }
            }
        })
    });

</script>

後臺:

UserCompleteController:

package com.buba.witkey.controller;

import com.buba.witkey.pojo.UserComplete;
import com.buba.witkey.service.UserCompleteService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RequestMapping("/corporation")
@Controller
public class UserCompleteController {
    @Resource
    private UserCompleteService userCompleteService;

   
    @RequestMapping("/sendFile1")
    @ResponseBody
    public Map<String,Object> sendFile1(MultipartFile file1, HttpSession session){
        Map<String,Object> map = new HashMap<>();
        map.put("flag",true);
        String realPath = session.getServletContext().getRealPath("/uploads/lisence");
        File temp = new File(realPath);
        if(!temp.exists()){
            //如果不存在,就新建一個路徑
            temp.mkdir();
        }
        String filename = file1.getOriginalFilename();
        //限制上傳的檔案必須是圖片,通過後綴名的方式
        String suffix = filename.substring(filename.lastIndexOf(".") + 1);
        if(!suffix.matches("^(?i)[(PNG)|(GIF)|(JPG)|(JPEG)]+$")){
            map.put("flag",false);
            map.put("message","請上傳圖片!");
            return map;
        }
        //如果圖片超過512M,返回false
        if(file1.getSize()>512*1024*1024){
            map.put("flag",false);
            map.put("message","檔案不支援>512KB!");
            return map;
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String format = sdf.format(new Date());
        filename = filename.substring(0,filename.lastIndexOf("."))+"_"+format+filename.substring(filename.lastIndexOf("."));
        File f = new File(realPath+File.separator+filename);
        try {
            file1.transferTo(f);
        } catch (IOException e) {
            e.printStackTrace();
            map.put("flag",false);
            map.put("message","上傳失敗,詳細資訊為:"+e.getMessage());
            return map;
        }
        map.put("filename",filename);
        return map;
    }
    
    @RequestMapping("/updateCorporation")
    @ResponseBody
    public boolean updateCorporation(UserComplete uc){
        int ucs = userCompleteService.updateCorporation(uc);
        if(ucs!=0){
            return true;
        }
        return false;
    }
   
    @RequestMapping("/showImages/{image:.+}")
    public void showImages(@PathVariable String image, HttpSession session, HttpServletResponse response){
        System.out.println("圖片名稱為:"+image);
        //獲取儲存圖片的絕對路徑
        String realPath = session.getServletContext().getRealPath("/uploads/lisence");
        File file  = new File(realPath+File.separator+image);
        try(FileInputStream fin = new FileInputStream(file);
            OutputStream out = response.getOutputStream();
        ) {
            byte[] buffer = new byte[1024];
            int count = 0;
            while ((count=fin.read(buffer))!=-1){
                out.write(buffer,0,count);
                out.flush();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

又over了!再見大兄弟們!