spring 上传下载文件

记录一下spring 上传下载文件的简单实现

上代码

controller

@RestController
@RequestMapping("/file")
public class FileUploadService {

    /**
     * 使用MultipartFile上传文件
     */
    @RequestMapping("/upload")
    public String fileUpload(
            @RequestParam(value = "file", required = false) MultipartFile file,
            HttpServletRequest request) {
        // 这个是项目所在的目录
        String path = request.getSession().getServletContext()
                .getRealPath("upload");
        System.out.println(path);
        String fileName = file.getOriginalFilename();
        File targetFile = new File(path, fileName);
        if (!targetFile.exists()) {
            targetFile.mkdirs();
        }
        // 保存
        try {
            file.transferTo(targetFile);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "view/success";
    }

    
    @RequestMapping("download")
    public ResponseEntity download(@RequestParam("fileName") String fileName,HttpServletRequest request)
            throws IOException {
        String path = request.getSession().getServletContext()
                .getRealPath("upload");
        // @RequestParam("fileName") 是utf-8编码的 在tomcat的server.xml里设定
        //
        File file = new File(path+"/"+fileName);
        
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        
        // 这个是用来下载时的文件名
        String dfileName = new String(fileName.getBytes("UTF-8"), "iso8859-1");
        headers.setContentDispositionFormData("attachment", dfileName);
        return new ResponseEntity(FileUtils.readFileToByteArray(file),
                headers, HttpStatus.CREATED);
    }

}

需要如下的spring 配置,我用的是java文件配置的方式

@Configuration
@ComponentScan(basePackages = {"business.**.services"},
    excludeFilters = {@ComponentScan.Filter(type = FilterType.ANNOTATION, value = EnableWebMvc.class)})
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {

    
    @Bean(name="multipartResolver") 
    public CommonsMultipartResolver multipartResolver() {
        System.out.println("multipartResolver");
        CommonsMultipartResolver resolver = new CommonsMultipartResolver();
        resolver.setMaxInMemorySize(40960);
        resolver.setMaxUploadSizePerFile(10485760000l);
        resolver.setDefaultEncoding("UTF-8");
        return resolver;
    }
   
//其他省略
}

页面

    

上传时 如果用form的话 将button改一下就好


如果用js的话 像下面这么写

    function upload() {
        if ($("#file").length == 0) return;
        //如果不想直接用form 可以这么写
        //var data = new FormData();
        //data.append("file",$("#file")[0].files[0]);
        $.ajax({
            url:'file/upload'
            ,type:'POST'
            ,data:new FormData($("#form0")[0])//直接用form
            ,cache : false
            ,processData : false
            ,contentType : false
            ,dataType:"json"//返回值
            ,success:function(ret){
                console.log("upload success")
            }
            ,error:function(ret){
                console.log("upload error")
                if (ret.status == 401) {
                    location = '/xufei2/index.html'
                }
            }
        })
    }

这里有个注意点 contentType一定要这样设置 否则会报错

contentType : false

上面的实现用到了两个jar
commons-fileupload-1.33.jar
commons-io-2.2.jar

maven这样

      
        commons-fileupload  
        commons-fileupload  
        1.3.3  
    

你可能感兴趣的:(spring 上传下载文件)