При загрузке файлов большего размера (особенно видео) с использованием пакета Spring-boot и java nio загружается только часть файла. Но файлы меньшего размера, такие как изображения, pdf и т. д., Загружаются правильно и могут использоваться.
Например: допустим, размер видео составляет 3,5 МБ, но при загрузке он показывает только 160 КБ и не может воспроизводить его ни в одном плеере (это потому, что, вероятно, частично загружено)
package com.filedownloader_with_nio_package.controllers;
import javax.servlet.ServletContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.filedownloader_with_nio_package.model.FileDetails;
import com.filedownloader_with_nio_package.services.FileDownloadService;
@RestController
public class FileDownloadController {
@Autowired
FileDownloadService fileDownloadService;
@RequestMapping(method = RequestMethod.POST, value = "/filedownload")
public String downloadFile(@RequestBody FileDetails fileDetails){
return fileDownloadService.downloadFile(fileDetails);
}
}
package com.filedownloader_with_nio_package.services;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;
import org.springframework.stereotype.Service;
import com.filedownloader_with_nio_package.exceptions.FileNotDownloadedCorrectlyException;
import com.filedownloader_with_nio_package.model.FileDetails;
import com.filedownloader_with_nio_package.utils.Constants;
@Service
public class FileDownloadService {
public String downloadFile(FileDetails fileDetails) {
try {
URL url = new URL(fileDetails.getFileUrl());
ReadableByteChannel readableByteChannel = Channels.newChannel(url
.openStream());
String downloadedFile = fileDetails.getFileDownloadLocation() + "/"
+ fileDetails.getFileName() + "."
+ fileDetails.getFileType();
FileOutputStream fileOutputStream = new FileOutputStream(
downloadedFile);
WritableByteChannel writableByteChannel = fileOutputStream
.getChannel();
//
//
ByteBuffer buffer = ByteBuffer.allocate(1024);
while (readableByteChannel.read(buffer) != -1) {
buffer.flip();
while (buffer.hasRemaining()) {
writableByteChannel.write(buffer);
}
buffer.clear();
}
//
//
fileOutputStream.flush();
fileOutputStream.close();
return downloadedFile;
} catch (MalformedURLException e) {
throw new FileNotDownloadedCorrectlyException(
Constants.FILE_NOT_DOWNLOADED_CORRECTLY, e);
} catch (IOException e) {
throw new FileNotDownloadedCorrectlyException(
Constants.FILE_NOT_DOWNLOADED_CORRECTLY, e);
}
}
}
package com.filedownloader_with_nio_package.model;
public class FileDetails {
private String fileName;
private String fileUrl;
private String fileType;
private String fileDownloadLocation;
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public String getFileUrl() {
return fileUrl;
}
public void setFileUrl(String fileUrl) {
this.fileUrl = fileUrl;
}
public String getFileType() {
return fileType;
}
public void setFileType(String fileType) {
this.fileType = fileType;
}
public String getFileDownloadLocation() {
return fileDownloadLocation;
}
public void setFileDownloadLocation(String fileDownloadLocation) {
this.fileDownloadLocation = fileDownloadLocation;
}
}
{
"fileName": "SB2",
"fileUrl": "https://drive.google.com/open?id=1_gkQK8sAlgTslzfRGOvNtbEAwtoPeyJv",
"fileType":"mp4",
"fileDownloadLocation": "C:/DownloadedFiles"
}
Я просмотрел соответствующие вопросы и ответы, но не смог найти для этого подходящего решения. Может ли кто-нибудь помочь разобраться в проблеме? или любая идея об этом приветствии.
Почему бы вам просто не использовать для этого Drive API? developers.google.com/drive/api/v3/manage-downloads
Требование @StephaneM не только для загрузки с диска Google, любая ссылка на файл из Интернета должна иметь возможность использовать.




вам понадобится url с extension для загрузки больших файлов (видео) при использовании пакетов nio.
URL url = new URL("https://elpvideo.s3-us-west-2.amazonaws.com/4445/4445.mp4");
Если ваша служба хостинга предоставляет API для загрузки файлов с определенным токеном, то nio packages не работает должным образом.
URL url = new URL("https://fv2-1.failiem.lv/down.php?i=sk2j3yuya");
кончик
если вы загружаете файл большого размера, обязательно установите timeout, если нет, то он будет отключен посередине.
URL url = new URL("https://elpvideo.s3-us-west-2.amazonaws.com/4445/4445.mp4");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setReadTimeout((1000*30)); //30 mins
ReadableByteChannel readableByteChannel = Channels.newChannel(urlConnection.getInputStream());
Дай угадаю - труп?