文件上传--有道笔记整理

来源:互联网 发布:js 类似sleep 编辑:程序博客网 时间:2024/04/29 10:15
html代码:
    <div style="width:800px;height:50px;">
            <input id="uploadFile" name="uploadFile" accept=".bmp,.gif,.jpeg,.png,.jpg" multiple="multiple" type="file" onchange="previewImagepr(this)" style="float:left;"/>
            <button id="confirmUpload" style="float:left;">确定上传</button>
           </div>
           <div id="preview">
           </div>
js代码:
var fileList = [];
var previewImagepr;
var isUploadPicture = false;
var isSubmit = false;
function showRemove(div){
  $(div).children('div').css({'height':'30px'});
}

function hideRemove(div){
 $(div).children('div').css({'height':'0px'});
}

function removePicture(span){
 $(span).parent('div').parent('div').remove();
// alert($(span).parent('div').parent('div').find('img').attr('id'));
 var id = $(span).parent('div').parent('div').find('img').attr('id');
 for(var index in fileList){
  if(id == fileList[index].id){
   fileList[index].id = -1;
   break;
  }
 }
}
//图片上传新技术
  var imageflag = 0;
  previewImagepr = function(file){
   isUploadPicture = true;
   var MAXWIDTH  = 100;
   var MAXHEIGHT = 100;
   var div = $('#preview');
   if (file.files){
    $.each(file.files,function(index,item){
     if((item.type == 'image/bmp') || (item.type == 'image/gif') || (item.type == 'image/jpeg') || (item.type == 'image/png')){
      // 目前仅支持这四种格式的图片
      //  alert('正确的图片格式');
// id初始值为0,flag初始值为1(有效);
      imgFile = {id:imageflag,flag:1,file:item};
      fileList[fileList.length] = imgFile; //从0开始
      div.append("<div onMouseOver='showRemove(this)' onMouseOut='hideRemove(this)' style='width:100px;height:100px;margin:3px;border:1px solid #000;float:left;'><div class='file-panel' style='height:0px;'><span class='cancel' onClick='removePicture(this)'>删除</span></div><img name='imghead' ></div>");
      var img = $('img[name=imghead]').last();
      img.attr('id',imageflag);
      imageflag++;
      var reader = new FileReader();
      reader.readAsDataURL(item);
      reader.onload = function(evt){
       img.attr('src',evt.target.result);
      }
      img.on('load',function(){
       var rect = clacImgZoomParam(MAXWIDTH, MAXHEIGHT, this.width, this.height);
       img.attr('width',rect.width);
       img.css({'marginLeft':rect.left,'marginTop':rect.top});
      });
     }
    });
   }else{

   }
  }
// 图片确定上传,图片上传.
  $('#confirmUpload').click(function(){
   if(isUploadPicture){
    isSubmit = true;
    isUploadPicture = false;
       var formdata=new FormData(this);
       for(var fl in fileList){
        // 当id为-1,即已经删除了,当flag为0,即已经上传过了的,
        if((fileList[fl].id == -1) || (fileList[fl].flag == 0))
         continue;
        formdata.append("fileUpload"+fl, fileList[fl].file);
        fileList[fl].flag = 0;
       }
       $.ajax({
           type:'POST',
           url:'${ctx}/uploadpic/productPicUpload.do',
           data:formdata,
           /**
            *必须false才会自动加上正确的Content-Type
            */
           contentType:false,
           /**
            * 必须false才会避开jQuery对 formdata 的默认处理
            * XMLHttpRequest会对 formdata 进行正确的处理
            */
           processData:false,
           success: function(dataa){
//         isUploadPicture = true;
                  var data = eval('('+ dataa +')');
                  alert('图片上传成功!');
                  $('#pictures').val($('#pictures').val() + data.resultDesc);
                 },
           error:function(){
//         isUploadPicture = true;
            for(var index in fileList){
             fileList[index].flag = 1;
            }
            alert('上传失败!');
           }
       });
//    isUploadPicture = true;
       return false;
   
   }else{
    alert('请先选择图片!');
   }
   
  });
//调整图片大小
  function clacImgZoomParam( maxWidth, maxHeight, width, height ){
   param = {width:0,height:0,left:0,top:0};
   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;
  }

后台java代码:
@RequestMapping(value="/uploadpic/productPicUpload.do", produces = { "text/plain;charset=UTF-8" })
 @ResponseBody
 public String productPicUpload(HttpServletRequest request,HttpServletResponse response) throws IllegalStateException, IOException {
  String realPath = request.getSession().getServletContext().getRealPath("/");
  //创建一个通用的多部分解析器
  CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
  //判断 request 是否有文件上传,即多部分请求
  if(multipartResolver.isMultipart(request)){
   //转换成多部分request  
   MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;
   //取得request中的所有文件名
   Iterator<String> iter = multiRequest.getFileNames();
   List<MultipartFile> fls = multiRequest.getFiles("uploadFile");
   String filePath = "upload" + File.separator + "image" + File.separator;
   String lastName = "";
   StringBuilder sBuilder = new StringBuilder("");
// StringBuilder sBuilder = new StringBuilder("{'fileUrl':'");
   while(iter.hasNext()){
    //记录上传过程起始时的时间,用来计算上传时间
    int pre = (int) System.currentTimeMillis();
    //取得上传文件
    String name = iter.next();
    List<MultipartFile> multipartFiles = multiRequest.getFiles(name);
    for (MultipartFile file : multipartFiles) {
     if(file != null){
      //取得当前上传文件的文件名称
      String myFileName = file.getOriginalFilename();
      //如果名称不为“”,说明该文件存在,否则说明该文件不存在
      if(myFileName.trim() !=""){
       System.out.println(myFileName);
       //重命名上传后的文件名
       String originalFileName = file.getOriginalFilename();
       String postFix = originalFileName.substring(originalFileName.lastIndexOf("."));
       String fileName = IDGenerator.generateID() + postFix;
       //定义上传路径
       String remotePaht = realPath + filePath + fileName;
       lastName = filePath + fileName;
       logger.info(remotePaht);
       sBuilder.append("../").append(lastName).append(";");
       File localFile = new File(remotePaht);
       file.transferTo(localFile);
      }
     }
    }
    //记录上传该文件后的时间
    int finaltime = (int) System.currentTimeMillis();
    System.out.println(finaltime - pre);
   }
// sBuilder.append("'}");
   
   
   System.out.println(sBuilder.toString().replaceAll("\\\\", "/"));
   Map<String, Object> resultMap = new HashMap<String, Object>();
   resultMap.put("result", "success");
   resultMap.put("resultDesc", sBuilder.toString().replaceAll("\\\\", "/"));
   return SpringAction.buildActionResult(resultMap);
   
// return sBuilder.toString().replaceAll("\\\\", "/");
  }
  return SpringAction.buildActionResult("error", "文件不能为空");
 }
0 0