java实现文件上传

java实现文件上传

前端页面

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
    <meta charset="UTF-8" />
    <title>Insert title here</title>
</head>
<body>
<h1 th:inlines="text">文件上传</h1>
<form action="地址" method="post" enctype="multipart/form-data">
    <p>选择文件: <input type="file" name="file"/></p>
    <p><input type="submit" value="提交"/></p>
</form>
</body>
</html>

使用enctype=“multipart/form-data” method="post"来表示进行文件上传

后端接口

@Slf4j
@RestController
public class UploadFileController {
    @PostMapping("/upload")
    public String upload(@RequestParam("file")MultipartFile file, HttpServletRequest request){
        try {
            if (file.isEmpty()){
                return "file is empty";
            }
            String filename = file.getOriginalFilename();
            log.info("上传文件名为:"+filename);
            //设置文件存储路径
            String filePath = "路径";
            String  path = filePath+filename;
            log.info("path为"+path);
            File dest = new File(path);
            if (!dest.getParentFile().exists()){
                dest.getParentFile().mkdirs(); //新建文件夹
            }
            file.transferTo(dest);//文件写入
            return "upload success";
        }catch (IllegalStateException e){
            e.printStackTrace();
        }catch (IOException e){
            e.printStackTrace();
        }
        return "upload failure";
    }
}
上一篇:strdup等c函数


下一篇:网络对抗实验一