检查互联网连接。Spring MVC下载文件。

huangapple go评论57阅读模式
英文:

check internet connection. Spring MVC Download file

问题

I've reviewed the code you provided, and it seems like there are no direct issues with connecting to the internet. The error message "check internet connection" is likely not related to your code, but rather a generic message indicating that there was a problem with the file download process.

Here are some observations and potential improvements in your code:

  1. File Paths: Make sure that the paths you have specified for UPLOAD_FOLDER and DOWNLOAD_FOLDER are correct and accessible. Verify that the application has the necessary permissions to read and write to these directories.

  2. Exception Handling: In your addNewFile method, you catch an IOException but do not provide any user-friendly error handling. You might want to log the error and provide a more informative error message to the user if there's an issue with file upload.

  3. Content Type: In your downloadFile method, you set the content type to "application/pdf," but it seems like you might be handling various types of files. Ensure that you set the appropriate content type based on the file type you are serving.

  4. Database Configuration: Verify that your database configuration in application.properties is correct and that the database server is running.

  5. Logging: Consider using more detailed logging throughout your code to help diagnose issues. Your current logger is quite minimal.

  6. Security: Ensure that your application is secure, especially when dealing with file uploads and downloads. Implement proper input validation and consider security best practices.

  7. Thymeleaf Template: Check your Thymeleaf template to ensure it correctly generates download links and handles file IDs.

Regarding the "check internet connection" message, this typically indicates a problem with the network or the URL you are trying to download from. It may not be directly related to your code but rather a network or server configuration issue.

To diagnose this issue further, you should:

  • Verify that the file you are trying to download exists in the specified path.
  • Ensure that the download URL is correct and points to a valid file location.
  • Check if there are any network or firewall issues that might be preventing the download.

It's essential to investigate these aspects outside of your code to identify the root cause of the download problem.

英文:

I have a project with which I learn to upload and download files, I implemented such a system, the file name, the path to it, its id and UUID are stored in the database (this is necessary so that there are no such problems when several files with the same name are uploaded) , everything works almost perfectly, but when I try to download a file, it says in my downloads: "check internet connection." screenshot: 检查互联网连接。Spring MVC下载文件。

FileEntity.class:

package instagram.entity;

import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.SequenceGenerator;
import jakarta.persistence.Table;

@Entity
@Table(name = "files")
public class FileEntity {

@Id
@SequenceGenerator(name = "file_seq", sequenceName = "file_seq", allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "file_seq")
private long id;

private String name;

private String path;

private String uuid;

public FileEntity() {}

public FileEntity(long id, String name, String path, String uuid) {
this.id = id;
this.name = name;
this.path = path;
this.uuid = uuid;
}

public FileEntity(String name, String path, String uuid) {
this.name = name;
this.path = path;
this.uuid = uuid;
}

public long getId() {
return id;
}

public void setId(long id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getPath() {
return path;
}

public void setPath(String path) {
this.path = path;
}

public String getUuid() {
return uuid;
}

public void setUuid(String uuid) {
this.uuid = uuid;
}

}

FileController.class:

package instagram.controller;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;
import java.util.logging.Logger;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import instagram.entity.FileEntity;
import instagram.service.FileService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

@Controller
public class FileController {

private FileService fileService;

private static Logger log = Logger.getGlobal();
private static String UPLOAD_FOLDER = "C://Users//SystemX//eclipse-workspace//instagram//lib//src//main//resources//images//";
private static String DOWNLOAD_FOLDER = "C://Users//SystemX//Downloads//";

public FileController(FileService fileService) {
this.fileService = fileService;
}

@GetMapping("/")
public String templateView(Model model) {
model.addAttribute("files", fileService.getAllFiles());
	
model.addAttribute("file", new FileEntity());
	
return "home";
}

@PostMapping("/")
public String addNewFile(@RequestParam(value = "file", required = false) MultipartFile multipart, Model model) {
if (multipart.isEmpty()) {
		
}
	
try {
String uuid = UUID.randomUUID().toString();
String newName = uuid + "." + multipart.getOriginalFilename();
		
byte[] bytes = multipart.getBytes();
Path path = Paths.get(UPLOAD_FOLDER + newName);
Files.write(path, bytes);
		
String[] newFile = newName.split("[.\\s]+");
		
fileService.saveNewFile(newFile);
		
} catch (IOException exception) {
exception.printStackTrace();
}
	
return "home";
}

@GetMapping("/download/{fileId}")
public String downloadFile(@PathVariable(value = "fileId") long fileId, Model model, HttpServletRequest request, HttpServletResponse response) {
	
FileEntity fileEntity = fileService.findById(fileId);
	
log.info(UPLOAD_FOLDER + fileEntity.getUuid() + "." + fileEntity.getName());
	
Path file = Paths.get(UPLOAD_FOLDER, fileEntity.getUuid() + "." + fileEntity.getName());
if (Files.exists(file)) {
response.setContentType("application/pdf");
response.addHeader("Content-Disposition", "attachment; filename=" + fileEntity.getName());
try {
Files.copy(file, response.getOutputStream());
response.getOutputStream().flush();
} catch (IOException ex) {
ex.printStackTrace();
}
}
	
return "home";
}

}

FileService.class:

package instagram.service;

import java.util.List;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import instagram.entity.FileEntity;
import instagram.repository.FileRepository;

@Service
public class FileService {

private FileRepository fileRepository;

@Autowired
public FileService(FileRepository fileRepository) {
this.fileRepository = fileRepository;
}

public List<FileEntity> getAllFiles() {
return fileRepository.findAll();
}

public FileEntity saveNewFile(String[] newFile) {
FileEntity file = new FileEntity();
	
file.setName(newFile[1] + "." + newFile[2]);
file.setPath("C://Users//SystemX//eclipse-workspace//instagram//lib//src//main//resources//images//");
file.setUuid(newFile[0]);
	
return fileRepository.save(file);
}

public FileEntity findById(long id) {
return fileRepository.findById(id);
}

}

FileRepository.interface:

package instagram.repository;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import instagram.entity.FileEntity;

@Repository
public interface FileRepository extends JpaRepository<FileEntity, Long> {

FileEntity findById(long id);

}

home.html:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>

<form th:method="POST" th:action="@{/}" enctype="multipart/form-data">
<input type="file" name="file"/>
<button type="submit">Send file</button>
</form>

<div th:each="newfiles: ${files}">
<a th:href="@{'/download/' + ${newfiles.id}}">
<span th:text="${newfiles.name}"></span>
</a>
</div>

</body>
</html>

application.properties:

spring.datasource.url=jdbc:postgresql://localhost:5432/instagram
spring.datasource.username=postgres
spring.datasource.password=

spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html

spring.servlet.multipart.enabled=true
spring.servlet.multipart.max-file-size=50MB
spring.servlet.multipart.max-request-size=50MB

spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=create-drop
spring.jpa.properties.hibernate.format_sql=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect

build.gradle:

dependencies {

testImplementation 'org.junit.jupiter:junit-jupiter:5.8.1'

api 'org.apache.commons:commons-math3:3.6.1'

implementation 'com.google.guava:guava:30.1.1-jre'

implementation 'org.springframework.boot:spring-boot-starter-web:3.1.0'

implementation 'org.springframework.boot:spring-boot-starter-data-jpa:3.1.0'

implementation 'org.postgresql:postgresql:42.6.0'

implementation 'org.springframework.boot:spring-boot-starter-thymeleaf:3.1.0'

implementation 'commons-io:commons-io:2.13.0'

}

what mistakes did I make in the implementation of the project and what exactly is the problem with connecting to the Internet?

答案1

得分: 0

After line:

response.getOutputStream().flush();

I added this:

response.getOutputStream().close();

Due to the fact that I didn't close the stream, he couldn't download the file, apparently that's why when I googled yesterday and a little today and didn't find a solution, good and happiness to everyone!

UDP:

By the way, on the topic of downloading a file from a folder, this code works well, the book was downloaded successfully!

UDP 2:

To avoid unnecessary problems in the console, I recommend changing the type of the method in which the file jump occurs to

void

and after

close();

write

return;

Download Method:

@GetMapping("/download/{fileId}")
public void downloadFile(@PathVariable(value = "fileId") long fileId, Model model, HttpServletRequest request, HttpServletResponse response) {

FileEntity fileEntity = fileService.findById(fileId);

log.info(UPLOAD_FOLDER + fileEntity.getUuid() + "." + fileEntity.getName());

Path file = Paths.get(UPLOAD_FOLDER, fileEntity.getUuid() + "." + fileEntity.getName());
if (Files.exists(file)) {
response.setContentType("application/pdf");
response.addHeader("Content-Disposition", "attachment; filename=" + fileEntity.getName());
try {
Files.copy(file, response.getOutputStream());
response.getOutputStream().flush();
response.getOutputStream().close();
return;
} catch (IOException ex) {
ex.printStackTrace();
}
}

return;
}

英文:

After line:

response.getOutputStream().flush();

I added this:

response.getOutputStream().close();

Due to the fact that I didn’t close the stream, he couldn’t download the file, apparently that’s why when I googled yesterday and a little today and didn’t find a solution, good and happiness to everyone!

UDP:

By the way, on the topic of downloading a file from a folder, this code works well, the book was downloaded successfully!

UDP 2:

To avoid unnecessary problems in the console, I recommend changing the type of the method in which the file jump occurs to

void

and after

close();

write

return;

Download Method:

@GetMapping("/download/{fileId}")
public void downloadFile(@PathVariable(value = "fileId") long fileId, Model model, HttpServletRequest request, HttpServletResponse response) {
	
FileEntity fileEntity = fileService.findById(fileId);
	
log.info(UPLOAD_FOLDER + fileEntity.getUuid() + "." + fileEntity.getName());
	
Path file = Paths.get(UPLOAD_FOLDER, fileEntity.getUuid() + "." + fileEntity.getName());
if (Files.exists(file)) {
response.setContentType("application/pdf");
response.addHeader("Content-Disposition", "attachment; filename=" + fileEntity.getName());
try {
Files.copy(file, response.getOutputStream());
response.getOutputStream().flush();
response.getOutputStream().close();
return;
} catch (IOException ex) {
ex.printStackTrace();
}
}
	
return;
}

huangapple
  • 本文由 发表于 2023年6月29日 19:52:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/76580779.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定