原创

java上传文件到OSS云服务器(一)

之前做springboot项目中遇到文件上传到OSS云服务器,然后把文件路径返回给手机端。文件上传是java web中常见的操作,文件上传主要是将文件通过IO流传放到云服务器
一、请求controller,暴露接口请求
@RestController()

public class UpLoadController {

@PostMapping("/uploadImFile")
public ResponseEntity uploadImFile(
        HttpServletRequest request,
        @RequestParam(value = "file") MultipartFile file) {
        return ResponseEntity.ok(userService.uploadImFile(request,file));}
}

二、service层,具体上传文件业务逻辑

@Override
public String uploadImFile(HttpServletRequest request, MultipartFile file) {
    String result='';
    try {
        long fileSize = file.getSize();
        if (fileSize > Long.parseLong(file_size)*1024*1024) {
            return result;
        }
        String path = request.getSession().getServletContext().getRealPath("/");
        String filename = file.getOriginalFilename();
        String fileSuffix = filename.substring(filename.lastIndexOf(".") + 1, filename.length());
        String fileNoSuffix = filename.substring(0, filename.lastIndexOf("."));
        if (null != file) {
            if (!"".equals(filename.trim())) {
                File newFile = new File(path, filename);
                FileOutputStream os = new FileOutputStream(newFile);
                os.write(file.getBytes());
                os.close();
                file.transferTo(newFile);
                String uploadUrl = null;
                uploadUrl = AliyunOSSUtil.uploadImFile(newFile,fileType);
                return uploadUrl;
            }
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return result;
}
至此,文件已经成功上传到OSS云服务器了,其中uploadUrl就是OSS 返回的文件路径。(注:回头再把OSS服务代码贴出来。)
正文到此结束
本文目录