springboot完成文件上传 15

springboot对文件上传和下载的支持是极为方便的。本节将阐述springboot中进行文件上传和下载。

1、环境约束

  • win10 64位操作系统
  • idea2018.1.5
  • maven-3.0.5
  • jdk-8u162-windows-x64

2、前提约束

3、操作步骤

  • 在主启动类同级目录下创建FileController.java:
import com.alibaba.fastjson.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;

@Controller
public class FileController {

    final String FILE_DEST_DIR = "D:/";
    @RequestMapping(value = "/filesystem/upload", method = RequestMethod.POST)
    @ResponseBody
    public JSONObject upload(HttpServletRequest request, MultipartFile file) {
        JSONObject jsonObject = new JSONObject();
        try {
            String filePath = FILE_DEST_DIR + file.getOriginalFilename();
            file.transferTo(new File(filePath));
            jsonObject.put("success","true");
            jsonObject.put("fileId",fastdfsPath);
        }
        catch (Exception e)
        {
            e.printStackTrace();
            jsonObject.put("success","false");
        }
        return jsonObject;
    }
}
  • 在项目/src/main/resources/static文件夹下创建index.html:
<!DOCTYPE html>
<html>
<head>
    <title>file upload</title>
</head>
<body>
<form action="/filesystem/upload" method="post" enctype="multipart/form-data">
    <input type="file" name="file" />
    <input type="submit" value="upload">
</form>
</body>
</html>
  • 测试
    启动主启动类,在浏览器中输入 http://localhost:8080/index.html ,根据提示操作,就可完成文件上传。
    以上就是使用springboot完成文件上传的过程,这个demo中做了好多默认配置。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值