手记

java实现文件上传文件的方法概述

上传文件前台代码
```<body>
<form method="post"action="upload.do"enctype="multipart/form-data" onsubmit="return checkSubmit();">
<div class="row cl">
<label class="form-label col-3"><span class="c-red">*</span>选择文件:</label>
<div class="formControls col-5">
<input type="file" id="uploadFile" name="file">
</div>
<div class="col-4"> <input type="submit" class="btn radius" name="Submit" value="上传"/></div>

</div>
</form>

function checkSubmit(){
var f = $('#uploadFile').val();
if(!f){
alert("请选择要上传的文件!");
return false;
}
return true;
}
</body>

上传文件后台dao层代码

//upPath:上传文件的路径 types:为上传文件的类型
public static String uploadOneFile(String upPath,String[] types,HttpServletRequest request){
MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) request;
MultipartFile mFile = mRequest.getFile("file");
String fileName = mFile.getOriginalFilename();
String storeName = rename(fileName);//给方法名重新命名(此方法在下面)
/遍历文件类型数组,类型匹配则上传文件返回true,否则上传失败返回false/
for(String type:types){
// getSuffix()方法根据转换后的文件名得到上传文件的后缀,即文件的类型(此方法在下面)
if(getSuffix(storeName).equals(type)){
try {
FileUtils.copyInputStreamToFile(mFile.getInputStream(), new File(upPath,storeName));
} catch (IOException e) {
e.printStackTrace();
}
return storeName;
}
}
return "fault";
}

/**

  • 将上传的文件进行重命名 采用当前日期+随机数
    */
    public static String rename(String name) {

    Long now = Long.parseLong(new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()));  
    Long random = (long) (Math.random() * now);  
    String fileName = now + "" + random;  
    
    if (name.indexOf(".") != -1) {  
        fileName += name.substring(name.lastIndexOf("."));  
    }  
    return fileName;  

    }

    /**

    • 根据转换后的文件名得到上传文件的后缀,即文件的类型
      */
      public static String getSuffix(String storename){
      String[] filename=storename.split("\.");
      String suffix=filename[filename.length-1];
      return suffix;
      }
上传文件后台controller层代码

@RequestMapping("/upload.do")
public String upload(HttpServletRequest request, ModelMap map) throws Exception {
//定义文件的类型
String format ="doc,docx,xls,xlsx,rar,zip,jpg,png,jpeg,pdf";
//文件要上传的路径
String uploadDir = request.getSession().getServletContext().getRealPath("/")+Constans.UPLOAD_FILE;
//uploadOneFile()上传单个文件的方法
String filename =this.uploadOneFile(uploadDir, format.split(","), request);
if("fault".equals(filename)){
map.put("fault", "文件类型不匹配或非法,请核实后重试!");
return "view/message/upload";//返回的页面
}
return "view/message/upload";
}

0人推荐
随时随地看视频
慕课网APP