Spring Boot上传文件并将其作为静态资源提供

时间:2018-01-24 13:45:50

标签: spring spring-boot file-upload static-resource

是否可以使用Spring / Spring Boot支持文件上传并将上传的文件作为静态资源提供?

我关注official tutorial以便我的应用可以处理文件上传,但是当我尝试将存储根目录设置为静态资源文件夹时,它无效。

我不想将文件上传到其他服务器或AWS S3。

如何使用Spring / Spring Boot支持文件上传并将上传的文件作为静态资源提供?

2 个答案:

答案 0 :(得分:0)

我对你的环境做了一些假设,但是这个怎么样:

将文件写入“somedirectory”,然后添加一个@Controller / @ RestController,查找这些文件并返回它们。

@RestController
public class UploadedFilesController {

  @ResponseMapping(value = "grabUploadedFile/{uploadedFileName}",method = RequestMethod.GET)
public ResponseEntity<File> getFile(@PathVariable String uploadedFileName){
  try{
    File toReturn = new File("somedirectory/" + uploadedFileName);
    ResponseEntity<File> r = new ResponseEntity(toReturn, HttpStatus.OK);
  }catch(Exception e){
    return new ResponseEntity(null, HttpStatus.NOT_FOUND);
  }
} 

答案 1 :(得分:0)

尝试这样的事情:

@RequestMapping(value = "/upload", method = RequestMethod.POST)
public ResponseEntity<Object> uploadFile(MultipartHttpServletRequest request) {

    final String UPLOAD_FOLDER = "C:\\Folder";

    try {
        request.setCharacterEncoding("UTF-8");
        Iterator<String> itr = request.getFileNames();

        while (itr.hasNext()) {
            String uploadedFile = itr.next();
            MultipartFile file = request.getFile(uploadedFile);
            String mimeType = file.getContentType();
            String filename = file.getOriginalFilename();
            byte[] bytes = file.getBytes();
            long size = file.getSize();

            FileUpload newFile = new FileUpload(filename, bytes, mimeType, size);

            String uploadedFileLocation = UPLOAD_FOLDER + newFile.getFilename();

            saveToFile(file.getInputStream(), uploadedFileLocation);

        }
    } catch (Exception e) {
        return new ResponseEntity<>("{INTERNAL_SERVER_ERROR}", HttpStatus.INTERNAL_SERVER_ERROR);
    }

    return new ResponseEntity<>("Message or Object", HttpStatus.OK);
}

}

private void saveToFile(InputStream inStream, String target) throws IOException {
    OutputStream out = null;
    int read = 0;
    byte[] bytes = new byte[1024];
    out = new FileOutputStream(new File(target));
    while ((read = inStream.read(bytes)) != -1) {
        out.write(bytes, 0, read);
    }
    out.flush();
    out.close();
}

}