文件上传到服务器(Java学习笔记)

  1. 首先创建一个Spring web项目
  2. 在resources/static目录下创建upload.html,页面代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>上传文件到服务器</title>
</head>
<body>
<form action="/upload" method="post" enctype="multipart/form-data">
    <input type="file" name="uploadFile" value="请选择文件夹">
    <input type="submit" value="上传">

</form>
</body>
</html>

  1. 创建文件上传的前端控制器类
package com.example.file;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.xml.ws.http.HTTPBinding;
import java.io.File;
import java.io.IOException;

/**
 * @author L葵乄阳S
 * @version 1.0
 * @description: TODO
 * @date 2023/5/23 14:01
 * @PROJECT_NAME JavaFoundation
 * @NAME UploadController.java
 */
@RestController
public class UploadController {
    @PostMapping("/upload")
    public String upload(MultipartFile uploadFile, HttpServletRequest request){
      String realPath =request.getSession().getServletContext().getRealPath("/uploadFile");
        File dir =new File(realPath);
        if (!dir.isDirectory()){
            dir.mkdir();
        }
        try{
            String fileName = uploadFile.getOriginalFilename();
//            服务器保存的文件对象
            File fileServer = new File(dir,fileName);
            System.out.println("file文件真实的路径:"+fileServer.getAbsolutePath());
//            2.实现上传
            uploadFile.transferTo(fileServer);
            String filePath = request.getScheme()+"://"+
                    request.getServerName()+":"
                    +request.getServerPort()
                    +"/uploadFile/"+fileName;
//            3.返回可访问的网络地址
            return filePath;
        }catch (IOException e){
            e.printStackTrace();
        }
        return "上传失败!";
    }

}

  1. 测试
    在这里插入图片描述

在这里插入图片描述
测试成功!

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值