0

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

我遵循官方教程 ,以便我的应用程序可以处理文件上传,但是当我尝试将存储根目录设置为静态资源文件夹时,它不起作用。

而且我不想将文件上传到另一台服务器或 AWS S3。

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

4

2 回答 2

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();
}

}

于 2018-01-24T14:59:57.957 回答
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);
  }
} 
于 2018-01-24T14:56:23.620 回答