SpringMVC的文件上传下载(同步和异步)

pom.xml 配置

 <dependency>  
    <groupId>commons-iogroupId>  
    <artifactId>commons-ioartifactId>  
    <version>2.4version>  
dependency>  

<dependency>  
    <groupId>commons-fileuploadgroupId>  
    <artifactId>commons-fileuploadartifactId>  
    <version>1.3version>  
dependency> 

**springMVC.xml配置**

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="10240000000"/>
<property name="defaultEncoding" value="utf-8"/>
bean>.

单个文件上传(上传后并显示出来)
前端JSP代码
//显示区域

 
请选择上传文件
    后台Java代码
    //ajax文件上传
@ResponseBody
@RequestMapping(value = "ajax_fileupload",method=RequestMethod.POST)
public String ajaxFileUpload(MultipartFile file,HttpServletRequest request) {
    Boolean mess = false;
    //解决文件名冲突
    String fileName = file.getOriginalFilename();
    String newFileName = UUID.randomUUID().toString()+fileName.substring(fileName.indexOf("."),fileName.length());
    String url = request.getSession().getServletContext().getRealPath("upload");
    System.out.println("url="+url);
    //如果目录不存在就创建一个
    if(!new File(url).exists()) {
        new File(url).mkdirs();
    }
    try {
        FileUtils.copyInputStreamToFile(file.getInputStream(), new File(url + File.separator + newFileName));
        mess = true;
    }catch(Exception e) {
        e.printStackTrace();
        mess = false;
    }
    JSONObject jsonObject = new JSONObject();
    jsonObject.put("mess", mess);
    jsonObject.put("url", File.separator+"upload"+File.separator+newFileName);
    return jsonObject.toJSONString();

}
“`
多个文件异步同时上传
前端JSP

你可能感兴趣的:(SpringMVC)