SpringBoot文件上传

SpringBoot文件上传

1.单文件上传

前端

<form enctype="multipart/form-data" action="http://localhost:40018/test/upload" method="post">
    <input type="" name="other" value="其他表单属性值" />
    <input type="file" name="file"/>
    <input type="submit" />
</form>

注意点:
1.enctype设置为multipart/form-data
	enctype的三个属性值
        application/x-www-form-urlencoded:在发送前编码所有字符(默认)
        multipart/form-data:不对字符编码。在使用包含文件上传控件的表单时,必须使用该值。
        text/plain:空格转换为 "+" 加号,但不对特殊字符编码。
2.method设置为post

后端

@PostMapping("upload")
public String upload(MultipartFile file,String other){
    InputStream is = null;
    OutputStream os = null;
    try {
        is = file.getInputStream();
        
        //对上传上来的文件进行其他处理,该处为将文件保存到本地
        os = new FileOutputStream(new File("F:\\test\\"+file.getOriginalFilename()));
        IOUtils.copy(is,os);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (is != null) is.close();
            if (os != null) os.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return "ok";
}

2.多文件上传

前端

<form enctype="multipart/form-data" action="http://localhost:40018/test/upload" method="post">
    <input type="text" name="other" value="其他表单属性值" />
    <input type="file" name="file"/>
    <input type="file" name="file"/>
    <input type="file" name="file"/>
    <input type="file" name="file"/>
    <input type="submit" />
</form>

注意点:
1.如果多个文件name值相同,后端用MultipartFile[]接收文件
2.如果多个文件name值不同,则用不同的MultipartFile对象接收文件

后端

@PostMapping("upload")
public String upload(MultipartFile[] file,String other){
    InputStream is = null;
    OutputStream os = null;
    try {
        for (MultipartFile item:file) {
            is = item.getInputStream();
            os = new FileOutputStream(new File("F:\\test\\"+item.getOriginalFilename()));
            IOUtils.copy(is,os);
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (is != null) is.close();
            if (os != null) os.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return "ok";
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值