java上传文件及下载文件

java上传下载

  • Controller
  • config.properties 配置文件
  • 访问路径
  • 实体类

Controller


@Api(tags = "附件上传")
//@UserLoginToken
@RestController
@RequestMapping("/fileController")
public class FileController {
    @Autowired
    private Config config;
    @ApiOperation("上传")
    @RequestMapping("/uploadFile")
    @ResponseBody
    public Response<String> uploadFile(@RequestParam MultipartFile file) {
        String fileName = file.getOriginalFilename();
        //系统目录
        String filePath = System.getProperty("user.dir") + config.getPicPath();
        java.io.File dest = new java.io.File(filePath + fileName);
        java.io.File pfile = new java.io.File(filePath);
        if (!pfile.exists()) {
            pfile.mkdirs();
        }
        if(dest.exists()){
            SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddmmss");
            fileName=sdf.format(Calendar.getInstance().getTime())+fileName;
            dest=new java.io.File(filePath+fileName);
        }
        try {
            file.transferTo(dest);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new Response<String>(ExpCodeState.upload_success, fileName);
    }

    /**
     * 下载
     * @param filename
     * @param response
     */
    @ApiOperation("下载")
    @RequestMapping("/{filename:.+}")
    @ResponseBody
    public void outPic(@PathVariable String filename, HttpServletResponse response) {
        java.io.File dest = new java.io.File(System.getProperty("user.dir") + config.getPicPath() + filename);
        try {
            ServletOutputStream out;
            try {
                @SuppressWarnings("resource")
                FileInputStream fis = new FileInputStream(dest);
                out = response.getOutputStream();
                int bytesRead = 0;
                byte[] buffer = new byte[819200];
                while ((bytesRead = fis.read(buffer, 0, 819200)) != -1) {
                    out.write(buffer, 0, bytesRead);
                }
                out.flush();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

config.properties 配置文件

property.picPath=/../negativeChecklist/

访问路径

http://xxx.xxx.x.xxx:8080/pmInfoApi/fileController/接口(1).txt

实体类

/**
 * Title: config.java
 * @author WuJin
 * @date 2020年3月28日
 * @version 1.0
 */
package com.pm.entity;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

import lombok.Data;

@PropertySource(value = { "classpath:config.properties" })
@ConfigurationProperties(prefix = "property")
@Component
@Data
public class Config {

	private String picPath;
}

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