前端文件上传时,java后端需要做的事

基础写法


@RequestMapping("/a")
//              ↓还有其他常规参数,放在这前面即可
public String FileUpdate (HttpServletRequest request,MultipartFile file) {
    //表示获得服务器的绝对路径

    //得到上传时的文件名字
    String originalname=file.getOriginalFilename();
    //substring(originalname.lastIndexOf(".")截取图片名后缀
    String newName= originalname.substring(originalname.lastIndexOf("."));
    //利用UUidUtil工具类生成新的文件名字
    newName = UUID.randomUUID().toString()+newName;

    String 文件放置位置="C:/Users/14779/Documents/IdeaProjects/qiyeji/src/main/resources/static";
    File newFile=new File(文件放置位置,newName);

    //获得文件目录,判断是否存在
    if(!newFile.getParentFile().exists()) {
        //如果path路径不存在,创建一个文件夹,存在则使用当前文件夹
        newFile.getParentFile().mkdirs();
    }
    try {
        //保存文件到指定路径之中
        file.transferTo(newFile);
    } catch (IllegalStateException | IOException e) {

        e.printStackTrace();
    }
    return 文件放置位置+newName;
}




放在static文件夹中的使用例子


    @ApiOperation(value = "_1_8_上传文件", notes="这里的参数只用关心前3个即可,切勿直接使用浏览器测试该api。<br>请使用vue的上传组件测试该api!")
    @RequestMapping(value = "/上传文件/{员工工号} {客户姓名} {项目编号}",method = RequestMethod.POST)
    public String _1_8_上传文件 (@PathVariable("员工工号") int  员工工号,@PathVariable("客户姓名") String   客户姓名,@PathVariable("项目编号") int   项目编号,
                              HttpServletRequest request, MultipartFile file) throws IOException {
        //表示获得服务器的绝对路径

        //得到上传时的文件名字
        String originalname=file.getOriginalFilename();
        //substring(originalname.lastIndexOf(".")截取图片名后缀
        String newName= originalname.substring(originalname.lastIndexOf("."));
        //利用UUidUtil工具类生成新的文件名字
        newName = UUID.randomUUID().toString()+newName;

        String 项目更目录 = new File("").getCanonicalPath() ;
        String 文件放置位置=项目更目录+"\\src\\main\\resources\\static\\"+员工工号+"\\";
        File newFile=new File(文件放置位置,newName);

        //获得文件目录,判断是否存在
        if(!newFile.getParentFile().exists()) {
            //如果path路径不存在,创建一个文件夹,存在则使用当前文件夹
            newFile.getParentFile().mkdirs();
        }
        try {
            //保存文件到指定路径之中
            file.transferTo(newFile);
        } catch (IllegalStateException | IOException e) {

            e.printStackTrace();
        }

        //生成 审核文件信息
        int 同部门主管的工号=service员工.返回和该员工同部门的主管的员工工号(员工工号);
        String 部门名=service员工.返回该员工的部门名(员工工号);
        service审核文件.插入新审核文件("localhost:1234/"+员工工号+"/"+newName,客户姓名,员工工号,项目编号,同部门主管的工号,部门名,0,"",0,"");

        return 文件放置位置+newName;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值