У меня есть код в весенний ботинок для загрузки файла. Уже удачно загружаем и помещаем файл в папку. Я уже получил код от работы с пакетной службой. Но я все еще путаю чтение данных CSV из загружаемых данных.
Хочу доработать. Когда я загружаю файл "особенно csv", система покажет данные в файле CSV.
Не могли бы вы мне помочь, как мне получить данные из CSV во время загрузки?
Контроллер
package com.mkyong.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
@Controller
public class UploadController {
//Save the uploaded file to this folder
private static String UPLOADED_FOLDER = "D:\\spring\\video\\";
@GetMapping("/")
public String index() {
return "upload";
}
@PostMapping("/upload") // //new annotation since 4.3
public String singleFileUpload(@RequestParam("file") MultipartFile file,
RedirectAttributes redirectAttributes) {
if (file.isEmpty()) {
redirectAttributes.addFlashAttribute("message", "Please select a file to upload");
return "redirect:uploadStatus";
}
try {
// Get the file and save it somewhere
byte[] bytes = file.getBytes();
Path path = Paths.get(UPLOADED_FOLDER + file.getOriginalFilename());
Files.write(path, bytes);
redirectAttributes.addFlashAttribute("message",
"You successfully uploaded '" + file.getOriginalFilename() + "'");
} catch (IOException e) {
e.printStackTrace();
}
return "redirect:/uploadStatus";
}
@GetMapping("/uploadStatus")
public String uploadStatus() {
return "uploadStatus";
}
}
МОДЕЛЬ
package com.mkyong.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "article")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@Column(name = "title")
private String title;
@Column(name = "category")
private String category;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
}
Вид
<!DOCTYPE html>
<html xmlns:th = "http://www.thymeleaf.org">
<body>
<h1>Spring Boot file upload example</h1>
<form method = "POST" action = "/upload" enctype = "multipart/form-data">
<input type = "file" name = "file" /><br/><br/>
<input type = "submit" value = "Submit" />
</form>
</body>
</html>
Меня искали на YouTube и на обучающем веб-сайте, но я не могу найти метод.




Вы можете попробовать это:
byte[] bytes = file.getBytes();
ByteArrayInputStream inputFilestream = new ByteArrayInputStream(bytes);
BufferedReader br = new BufferedReader(new InputStreamReader(inputFilestream ));
String line = "";
while ((line = br.readLine()) != null) {
System.out.println(line);
}
br.close();
1. класс модели = Listing.java
.csv присутствует в resources/static/listing.csvprivate void createListingFromCsvRecord() {
String path = "classpath:static/listings.csv";
ResultSet rs = new Csv().read(path, null, null);
List<Listing> list = new ArrayList<>();
while (rs.next()) {
Listing listing = new Listing();
listing.setListingId(Long.parseLong(rs.getString("listingId")));
listing.setSiteArea(rs.getString("siteArea"));
list.add(listing);
}
myrepo.saveAll(list);
}