SpringBoot实现文件上传

用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>

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



阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/xxkalychen/article/details/77842638
想对作者说点什么? 我来说一句

SpringBoot上传文件实例下载

2017年03月11日 96KB 下载

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭