我试图使用spring boot,我想创建一个上传文件的应用程序并返回它的哈希值。 我已成功上传文件,但我不知道如何将其哈希值返回到新的html(或相同的html页面)。能否请你帮忙?这是我的代码:
@Controller
public class FileUploadController {
@PostMapping("/")
public String handleFileUpload(@RequestParam("file") MultipartFile file,
RedirectAttributes redirectAttributes) throws NoSuchAlgorithmException, IOException {
byte[] fileBytes = file.getBytes();
MessageDigest sha256 = MessageDigest.getInstance("SHA-256");
byte[] digest = sha256.digest(fileBytes);
String hashString = new BigInteger(1, digest).toString(16);
System.out.println("File hash: " + hashString);
return "redirect:/test.html";
}
和html:
<form method="POST" enctype="multipart/form-data" action="/">
<table>
<tr>
<td>File to upload:</td>
<td><input type="file" name="file" /></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Upload" /></td>
</tr>
</table>
</form>
答案 0 :(得分:0)
您已在代码中使用它了。使用Mouse
RedirectAttributes
然后从新页面的请求参数中获取该属性。
答案 1 :(得分:0)
我已经做过研究,发现返回值的方法之一是使用百万美元资源,所以我的代码现在就像这样,它可以工作! 包com.boot.test10.controller;
import java.io.IOException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
@Controller
public class ViewController {
private String sha256String;
@RequestMapping("/")
public String Test(){
return "index";
}
@RequestMapping("/hash")
public String index(Model model){
model.addAttribute("hash", sha256String);
return "hash";
}
@PostMapping("/")
public String handleFileUpload(@RequestParam("file") MultipartFile file,
RedirectAttributes redirectAttributes) throws IOException,
`enter code here`NoSuchAlgorithmException {
byte[] fileBytes = file.getBytes();
MessageDigest sha256 = MessageDigest.getInstance("SHA-256");
byte[] digest = sha256.digest(fileBytes);
String sha256String = new BigInteger(1, digest).toString(16);
this.sha256String = sha256String;
return "redirect:/hash";
}
}
并且html是这样的:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8" />
<title>Test Me</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous" />
</head>
<body>
<p th:text="'The Hash Of The File Is: ' + ${hash}"></p>
</body>
</html>