Отображение файла на веб-странице с использованием AJAX и Spring Boot - PullRequest
0 голосов
/ 01 апреля 2020

Я создаю REST API в Spring Boot для загрузки и извлечения файлов с сервера, я хочу загружать различные типы файлов, которые могут быть текстовыми, графическими, аудио, видео и т. Д. c ..

При загрузке проблем нет, но когда я хочу отобразить файл на своей веб-странице, появляется контент, но я получаю данные с сервера в виде необработанных данных.

Я хочу поместить эти данные в URL.createObjectURL () и затем перенаправить на сгенерированный URL.

Есть несколько снимков экрана, которые я загружаю.

Это данные, когда я выполняю консоль. войти (ответ); enter image description here

Код, который я использую для AJAX

var form = new FormData();
form.append("qualifiedFilePath", "E://files/test.png");

var settings = {
    "async": true,
    "crossDomain": true,
    "url": "http://localhost:8081/callTransaction/file",
    "method": "POST",
    "timeout": 0,
    "processData": false,
    "mimeType": "multipart/form-data",
    "contentType": false,
    "Accept": "image/png",
    "data": form
};

$.ajax(settings).done(function(response) {
    console.log(response);
    const objectURL = URL.createObjectURL(new Blob([response], {
        "type": "image/png"
    }));
    console.log(objectURL);
});

Я получаю URL: blob: http://localhost: 8080 / 81c9fbde-5e84-400e-8d92-5da6fc02c7ef

Вывод:

enter image description here

Исходный код в Spring Boot:

Контроллер:

@PostMapping(path="/file")
@CrossOrigin(origins = "http://localhost:8080")
public ResponseEntity<Resource> loadFile(@RequestPart("qualifiedFilePath") String qualifiedFilePath, HttpServletRequest request)
{
    return ctbl.loadFile(qualifiedFilePath,request);
}

BusinessLogi c:

public ResponseEntity<Resource> loadFile(String qualifiedFilePath, HttpServletRequest request)
    {
        Resource file=null;
        if(qualifiedFilePath==null)
        {
            return new ResponseEntity<Resource>(file,HttpStatus.BAD_REQUEST);
        }
        try {
            file=ctdi.loadFile(qualifiedFilePath);
        } catch (MalformedURLException e) {
            return new ResponseEntity<Resource>(file,HttpStatus.INTERNAL_SERVER_ERROR);
        }
        if(file==null)
        {
            return new ResponseEntity<Resource>(file,HttpStatus.NO_CONTENT);
        }
          String contentType = null;
            try {
                contentType = request.getServletContext().getMimeType(file.getFile().getAbsolutePath());
            } catch (IOException ex) {
                return new ResponseEntity<Resource>(file,HttpStatus.INTERNAL_SERVER_ERROR);
            }

            if(contentType == null) {
                contentType = "application/octet-stream";
            }
            return ResponseEntity.ok()
                                .contentType(MediaType.parseMediaType(contentType))
                                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + file.getFilename() + "\"")
                                .body(file);
    }

DAO:

@Override
public Resource loadFile(String qualifiedFilePath) throws MalformedURLException {
    Path filePath = Paths.get(qualifiedFilePath);
    Resource resource = new UrlResource(filePath.toUri());
    return resource;
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...