Jojo的作业系统

简单的文件上传

代码如下

@RestController
@RequestMapping("/file")
public class FileController {
    @RequestMapping(method = RequestMethod.POST, value ="/upload")
    @ResponseBody
    public String uploadFile(@RequestParam("fileName") MultipartFile file) throws IOException {
        System.out.println("file name = "+file.getOriginalFilename());
        if (file.isEmpty()) {
            return "file is empty";
        }
        // 获取文件名
        String fileName = file.getOriginalFilename();
        // 获取后缀
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        // 文件上产的路径
        String filePath = "d:\\macro";
        // fileName处理
//        fileName = filePath+ UUID.randomUUID()+fileName;
        fileName = filePath+ Path.SEPARATOR+fileName;
        // 文件对象
        File dest = new File(fileName);
        // 创建路径
        if(!dest.getParentFile().exists()){
            dest.getParentFile().mkdir();
        }

        try {
            file.transferTo(dest);
            return "上传成功";
        } catch (IOException e) {
            e.printStackTrace();
            throw e;
        }

    }

    @RequestMapping("download")
    public void download(HttpServletResponse response) throws FileNotFoundException {
        File file =new File("C:\\Users\\ASUS\\Desktop\\spring-boot-reference.pdf");
        FileInputStream fileInputStream=new FileInputStream(file);
        // 设置被下载而不是被打开
        response.setContentType("application/gorce-download");
        // 设置被第三方工具打开,设置下载的文件名
        response.addHeader("Content-disposition","attachment;fileName=spring-boot-reference.pdf");
        try {
            OutputStream outputStream = response.getOutputStream();
            byte[] bytes = new byte[1024];
            int len = 0;
            while ((len = fileInputStream.read(bytes))!=-1){
                outputStream.write(bytes,0,len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Postman的设置,注意不要添加任何header
Jojo的作业系统_第1张图片

引入注册登录系统

你可能感兴趣的:(Java)