html選擇圖片後預覽,保存並上傳

html代碼:
------------------添加--------------------------
accept="image/gif,image/jpeg,image/jpg,image/png"
使用這個可讓用戶只能看到並上傳圖片
本來是這個accept="image/*"的,後來發如今Chrome瀏覽器上響應過慢,因此加上mime類型,避免所有匹配引發時的瀏覽器響應過慢問題
<input type="file" id="file" style="display:none;" onchange="filechange(event)">//修改,這裏若是不用onchange,會出現一個小bug,當你提交後,圖片只能變一次
<img src="" width="200px" height="200px" id="img-change">
<button id="btn">保存圖片</button>
js代碼:
//實現點擊圖片同時,觸發type=file這個input
$("#img-change").click(function () {
    $("#file").click();
})
當input發生改變時,若是有圖片,則預覽圖片(這裏只判斷文件的改變,沒判斷圖片)
/*$("#file").change(function (event) {*/
var filechange=function(event){
var files = event.target.files, file; if (files && files.length > 0) { // 獲取目前上傳的文件 file = files[0];// 文件大小校驗的動做 if(file.size > 1024 * 1024 * 2) { alert('圖片大小不能超過 2MB!'); return false; } // 獲取 window 的 URL 工具 var URL = window.URL || window.webkitURL; // 經過 file 生成目標 url var imgURL = URL.createObjectURL(file); //用attr將img的src屬性改爲得到的url $("#img-change").attr("src",imgURL); // 使用下面這句能夠在內存中釋放對此 url 的伺服,跑了以後那個 URL 就無效了 // URL.revokeObjectURL(imgURL); } };

 接下來實現當點擊按鈕時,經過jquey的一個插件ajaxupload來進行上傳圖片,css

代碼以下:html

$("#btn").click(function () {
        $.ajaxFileUpload({
            url: '/imgUpload',
            fileElementId:'file',
            dataType:'txt',
            secureuri : false,
            success: function (data){
                if(data=="yes"){
                    $("#img-alert").css("display","block");
                }
            },
            error:function(data,status,e){
                alert(e);
            }
        });
    });

接下來是後臺代碼,個人後臺是spring mvc框架,我沒試過不用spring mvc的框架,但最多在攔截時不一樣,獲得後,在文件處理那塊是同樣的java

@RequestMapping(value = "/imgUpload")
    @ResponseBody
    public synchronized String imgUpload(@RequestParam("file") MultipartFile file,HttpServletRequest request) throws IOException {
        String tishi="no";
        System.out.println("arrive here");
        if(!file.isEmpty()) {
            //System.out.println(file.getOriginalFilename());
            String message = System.currentTimeMillis() + file.getOriginalFilename();//如今的文件名是時間戳加原文件名,出現圖片相同時,讀取不出來的bug
            String realPath = request.getSession().getServletContext().getRealPath("/upload/");//將文件保存在當前工程下的一個upload文件
            FileUtils.copyInputStreamToFile(file.getInputStream(), new File(realPath, message));//將文件的輸入流輸出到一個新的文件
            message="upload/"+message;
            HttpSession session=request.getSession();
            Integer id=(Integer)session.getAttribute("userid");//在session中得到用戶id
            User user=userService.get(id);//在dao層保存數據,也就是圖片的地址
            user.setPhoto(message);
            userService.update(user);
            tishi="yes";//返回yes,表示存儲成功,可使用try,catch來捕捉錯誤,這裏偷懶不用
        }
        return tishi;
    }

  還有一點,還需再spring mvc框架下配置文件web

<bean id="multipartResolver"
          class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="defaultEncoding" value="utf-8" />
        <property name="maxUploadSize" value="1048576000" />
        <property name="maxInMemorySize" value="40960000" />
    </bean>
相關文章
相關標籤/搜索