SpringBoot实现文件上传

51 篇文章 1 订阅
33 篇文章 1 订阅

用SpringBoot实现服务器,然后用java和html5实现客户端进行上传测试。

一、服务器端接口程序。为省事就在controller中写了,正式的程序我喜欢放在service这一层进行处理调用。

@RestController
@RequestMapping("/file")
public class FileController {
    /**
     * 单文件上传
     *
     * @param file
     * @param request
     * @return
     */
    @PostMapping("/upload")
    @ResponseBody
    public String upload(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
        if (!file.isEmpty()) {
            String saveFileName = file.getOriginalFilename();
            File saveFile = new File(request.getSession().getServletContext().getRealPath("/upload/") + saveFileName);
            if (!saveFile.getParentFile().exists()) {
                saveFile.getParentFile().mkdirs();
            }
            try {
                BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(saveFile));
                out.write(file.getBytes());
                out.flush();
                out.close();
                return ResultUtils.buildResult(saveFile.getName() + " 上传成功");
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                return ResultUtils.buildResult("上传失败," + e.getMessage());
            } catch (IOException e) {
                e.printStackTrace();
                return ResultUtils.buildResult("上传失败," + e.getMessage());
            }
        } else {
            return ResultUtils.buildResult("上传失败,因为文件为空.");
        }
    }

    /**
     * 多文件上传
     *
     * @param request
     * @return
     */
    @PostMapping("/uploadFiles")
    @ResponseBody
    public String uploadFiles(HttpServletRequest request) throws IOException {
        File savePath = new File(request.getSession().getServletContext().getRealPath("/upload/"));
        if (!savePath.exists()) {
            savePath.mkdirs();
        }
        List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file");
        MultipartFile file = null;
        BufferedOutputStream stream = null;
        for (int i = 0; i < files.size(); ++i) {
            file = files.get(i);
            if (!file.isEmpty()) {
                try {
                    byte[] bytes = file.getBytes();
                    File saveFile = new File(savePath, file.getOriginalFilename());
                    stream = new BufferedOutputStream(new FileOutputStream(saveFile));
                    stream.write(bytes);
                    stream.close();
                } catch (Exception e) {
                    if (stream != null) {
                        stream.close();
                        stream = null;
                    }
                    return "第 " + i + " 个文件上传有错误" + e.getMessage();
                }
            } else {
                return "第 " + i + " 个文件为空";
            }
        }
        return "所有文件上传成功";
    }
}
但是大于1MB的文件上传时会提示出错的,所以要进行设置。添加一个配置文件就可以了。

@Configuration
public class FileUploadConfig {

    @Bean
    public MultipartConfigElement multipartConfigElement() {
        MultipartConfigFactory factory = new MultipartConfigFactory();
        factory.setMaxFileSize("100MB"); 
        factory.setMaxRequestSize("100MB");
        return factory.createMultipartConfig();
    }
}
也可以在application.properties中加入这两句:


spring.http.multipart.maxFileSize=100Mb
spring.http.multipart.maxRequestSize=100Mb

二者选其一即可。

2.java客户端测试程序,Android端也是如此,我是用retrofit2框架,以下是三部分代码:

接口:

public interface TestService {

    //文件上传
    @Multipart
    @POST("upload")
    Call<NetResult<Object>> upload(@Part MultipartBody.Part part);

}

API部分:

public class TestApi extends NetApi {
    private static String BASE_URL = "http://192.168.1.101:8080/springbootdemo/file/";
    private static TestService service = NetClient.getRetrofit(BASE_URL).create(TestService.class);
    
    //文件上传
    public static void upload(File file, NetCallback<Object> callback) {
        RequestBody body = RequestBody.create(MediaType.parse("multipart/form-data"), file);
        MultipartBody.Part part = MultipartBody.Part.createFormData("file", file.getName(), body);
        Call call = service.upload(part);
        call.enqueue(callback);
        NetManager.addRequest(call);
    }

}

测试调用:

public class Test {
    public static void main(String[] args) {
        String filePath = "E://被遗忘的时光.ape";
        File file = new File(filePath);
        NetCallback<Object> callback = new NetCallback<Object>() {
            @Override
            protected void onComplete(NetResponse<Object> netResponse) {
            }
        };
        TestApi.upload(file, callback);
    }
}

测试成功上传!!!

三、HTML5页面单文件上传和多文件上传

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
<form action="http://192.168.1.101:8080/springbootdemo/file/upload"
      method="post"
      enctype="multipart/form-data">
    文件:<input type="file" name="file"/>
    <input type="submit" value="上传"/>
</form>
</body>
</html>

测试成功!!!!!!!!!!!!!!!!!!!!!!!



  • 5
    点赞
  • 28
    收藏
    觉得还不错? 一键收藏
  • 9
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值