java web文件上傳

html

<form  id="form_upload" enctype="multipart/form-data">
                                      <input  type="hidden" name="uid"  id="upload_uid">
                                      <input  type="hidden" name="sid"  id="upload_sid">
                                      <div id="upload_fileArea">
                                          <input type="file"  class="btn_mask" οnchange="previewImage(this)"  name="picture" style="display: none;" id="previewImg">
                                      </div>

                                      <span id="upload_include">
                                          <span οnclick="upload_file()" class="btn btn-default btn_upload" id="btn_upload_file"><span class="glyphicon glyphicon-picture">上傳圖片</span></span>
                                      </span>

                                  </form>

js

/****遮罩層現實和隱藏****/
function upload(sid,sTitle){
    $.get("user/findOne",{},function (user) {
        if (user){
            $(".shadow_upload").css({'display':'block'});
            $('#upload_title').html(sTitle);
            $('#upload_sid').val(sid);
            var uid=user.uid;
            $.get("fileUpload/findStatus",{uid:uid,sid:sid},function (info) {
               if (info.flag){

               }else {
                   var text=' <span class="btn btn-default btn_upload" id="btn_upload_file"><span class="glyphicon glyphicon-picture">上傳圖片</span></span>';
                   $('#upload_include').html(text);
                   $('#btn_upload_file').attr("disabled",true);
                   $('#message').html(info.errorMsg).show().delay(2000).fadeOut();
               }
            });
        }else {
           alert("請先進行登錄!");
           location.href="user_login.html";
        }


    });

}
$('#btn_close').click(function () {
    $('.shadow').hide();
    Refresh();
});
/***********圖片預覽**************/
//圖片上傳預覽    IE是用了濾鏡。
function previewImage(file)
{
    var MAXWIDTH  = 130;
    var MAXHEIGHT = 130;
    var div = document.getElementById('preview');
    if (file.files && file.files[0])
    {
        div.innerHTML ='<img id=imghead οnclick=$("#previewImg").click()>';
        var img = document.getElementById('imghead');
        img.onload = function(){
            var rect = clacImgZoomParam(MAXWIDTH, MAXHEIGHT, img.offsetWidth, img.offsetHeight);
            img.width  =  rect.width;
            img.height =  rect.height;
//                 img.style.marginLeft = rect.left+'px';
            img.style.marginTop = rect.top+'px';
        }
        var reader = new FileReader();
        reader.onload = function(evt){img.src = evt.target.result;}
        reader.readAsDataURL(file.files[0]);
    }
    else //兼容IE
    {
        var sFilter='filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale,src="';
        file.select();
        var src = document.selection.createRange().text;
        div.innerHTML = '<img id=imghead>';
        var img = document.getElementById('imghead');
        img.filters.item('DXImageTransform.Microsoft.AlphaImageLoader').src = src;
        var rect = clacImgZoomParam(MAXWIDTH, MAXHEIGHT, img.offsetWidth, img.offsetHeight);
        status =('rect:'+rect.top+','+rect.left+','+rect.width+','+rect.height);
        div.innerHTML = "<div id=divhead style='width:"+rect.width+"px;height:"+rect.height+"px;margin-top:"+rect.top+"px;"+sFilter+src+"\"'></div>";
    }
}
function clacImgZoomParam( maxWidth, maxHeight, width, height ){
    var param = {top:0, left:0, width:width, height:height};
    if( width>maxWidth || height>maxHeight ){
        rateWidth = width / maxWidth;
        rateHeight = height / maxHeight;

        if( rateWidth > rateHeight ){
            param.width =  maxWidth;
            param.height = Math.round(height / rateWidth);
        }else{
            param.width = Math.round(width / rateHeight);
            param.height = maxHeight;
        }
    }
    param.left = Math.round((maxWidth - param.width) / 2);
    param.top = Math.round((maxHeight - param.height) / 2);
    return param;
}
/************圖片上傳*****************/
function upload_file(ele) {
    //判斷是否有文件
    var fileinput=$('#previewImg').get(0).files[0];
    if (fileinput){
        var filePath=$("#previewImg").val();
        //截取後綴名
        var extStart=filePath.lastIndexOf(".");
        var ext=filePath.substring(extStart,filePath.length).toUpperCase();
        if (ext==".BMP"||ext==".PNG"||ext==".JPG"||ext==".JPEG"||ext==".GIF"||ext==".doc"||ext==".docx"||ext==".txt"){
            //獲取文件大小
            var filesize=$('#previewImg')[0].files[0].size;
            if (filesize<1024*1024){
                var formData=new FormData($('#form_upload')[0]);
                // $.post("upload/file",formData,function (info) {
                //
                // });
                $.ajax({
                    type:'post',
                    url:"http://localhost:8055/firstblog/fileUpload/file",
                    data:formData,
                    cache:false,
                    processData:false,
                    contentType:false,
                    success:function () {
                        $('#message').html("上傳成功").show().delay(2000).fadeOut();
                        setTimeout(Refresh,2000);
                    },
                    error:function () {
                        $('#message').html("上傳失敗").show().delay(2000).fadeOut();
                    }
                });
            }else {
                alert("圖片不能大於1M")
            }


        }else {
            alert("文件限於bmp,png,gif,jpeg,jpg,doc,docx,txt格式");
            return false;
        }

    }else {
        alert("請選擇上傳文件");
    }
}
/*******刷新******/
function Refresh() {
    window.location.href=window.location.href;

}

後臺
servlet

public void file(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //設置編碼
        response.setContentType("text/html;charset=utf-8");
        request.setCharacterEncoding("utf-8");
        response.setContentType("utf-8");
        //上傳

        Map<String,String> params=new HashMap<String,String>();
        ResultInfo info=new ResultInfo();
        FileUpload fileUpload=new FileUpload();
        boolean isMultipart= ServletFileUpload.isMultipartContent(request);
        if (isMultipart){//判斷前臺是否有mutipart屬性
            FileItemFactory factory=new DiskFileItemFactory();
            ServletFileUpload stf=new ServletFileUpload(factory);
            //設置每一個item的頭部字符編碼,解決文件名的亂碼問題
            stf.setHeaderEncoding("UTF-8");
//            //限制單個文件大小爲1M
//            stf.setFileSizeMax(1024*1024);
//            //設置一次上傳所有文件的最大值爲5M
//            stf.setSizeMax(1024*1024*5);
            /**
             * 通過parseRequest解析from中的所有請求字段,並保存到items集合中
             * 即前臺傳地的spicture就保存在items中
             */
            List<FileItem> items=stf.parseRequest(request);

         for (FileItem fileItem:items){
             //判斷前臺字段是普通form表單字段,還是文件字段
             if (fileItem.isFormField()){
                 String name=fileItem.getFieldName();
                 String value=fileItem.getString("utf-8");
                 params.put(name,value);
                 String uid=params.get("uid");
                 String sid=params.get("sid");
                 String text_info=params.get("info");
                 if (uid !=null){
                     fileUpload.setUid(Integer.parseInt(uid));
                 }
                 if (sid != null){
                     fileUpload.setSid(Integer.parseInt(sid));
                 }
                 if (text_info != null){
                     fileUpload.setInfo(text_info);
                 }
             }else {//picture
                 //文件上傳
                 //文件名 getFiledName是獲取普通表單字段的Name值
                 //getName()是獲取文件名
                 String fileName= UuidUtil.getUuid()+"_"+fileItem.getName();
                 //獲取文件內容並上傳位置(服務器路徑)
                 //獲取服務器路徑
                 //定義文件路徑
                 String date= LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
                 String path=request.getSession().getServletContext().getRealPath("upload/img/"+date);
                 File file=new File(path);
                 if (!file.exists()){
                     file.mkdirs();
                 }
                 File files=new File(path,fileName);
                 //獲取文件大小
                 long size=fileItem.getSize();
                 //取整
                 size=Math.round(size/1024);
                 //文件寫入
                 fileItem.write(files);
                 //封裝數據

                 fileUpload.setfName(fileName);
                 //長整型轉字符串
                 fileUpload.setfSize(String.valueOf(size));
                 //獲取文件上傳時間
                 String dateTime= LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                 fileUpload.setfAddTime(dateTime);
                 //保存上傳路徑
                 fileUpload.setFile_path(path);
                 System.out.println(fileUpload.getUid()+fileUpload.getSid());
             }
         }


        }
        System.out.println(fileUpload.getUid()+fileUpload.getSid());
        boolean flag=service.save(fileUpload);
        if (flag){
            info.setFlag(true);
            System.out.println("fileName"+"上傳成功");
        }else {
            info.setFlag(false);
            info.setErrorMsg("上傳失敗!");
        }
        ObjectMapper mapper=new ObjectMapper();
        response.setContentType("application/json;charset=utf-8");
        mapper.writeValue(response.getOutputStream(),info);
    }

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章