下面我将详细讲解“Java实战之实现文件资料上传并生成缩略图”的完整攻略。
目录
- 资料上传的步骤
- 生成缩略图的步骤
- 示例一:使用Spring MVC实现文件上传
- 示例二:使用Apache Commons FileUpload实现文件上传
资料上传的步骤
- 在前端页面上添加文件上传表单,并设置相应的属性。
<form action="#" method="POST" enctype="multipart/form-data">
<input type="file" name="file">
<button type="submit">提交</button>
</form>
-
在服务器端接收上传的文件,可以使用Spring MVC框架或Apache Commons FileUpload组件等。
-
对文件进行处理(例如重命名、存储到指定目录等)。
-
返回上传结果给前端页面。
生成缩略图的步骤
- 使用Java自带的ImageIO类加载上传的图片。
File file = new File("path/to/image.jpg");
BufferedImage img = ImageIO.read(file);
- 调整图片尺寸。
int width = img.getWidth();
int height = img.getHeight();
int newWidth = 100; // 新的宽度
int newHeight = height * newWidth / width; // 新的高度按比例计算
Image scaledImage = img.getScaledInstance(newWidth, newHeight, Image.SCALE_SMOOTH);
- 保存缩略图至指定目录。
BufferedImage thumbnail = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = thumbnail.createGraphics();
g2d.drawImage(scaledImage, 0, 0, null);
g2d.dispose();
File thumbnailFile = new File("path/to/thumbnail.jpg");
ImageIO.write(thumbnail, "jpg", thumbnailFile);
- 返回缩略图文件名或URL。
示例一:使用Spring MVC实现文件上传
- 在pom.xml中添加依赖。
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.3.10</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.10</version>
</dependency>
- 添加上传文件的Controller。
@Controller
public class UploadController {
@RequestMapping(value = "/upload", method = RequestMethod.POST)
public String upload(@RequestParam("file") MultipartFile file, ModelMap model) throws IOException {
String originalFilename = file.getOriginalFilename();
String extension = FileUtils.getFileExtension(originalFilename);
String newName = UUID.randomUUID().toString() + "." + extension;
File newFile = new File("path/to/uploaded/" + newName);
file.transferTo(newFile);
BufferedImage img = ImageIO.read(newFile);
int width = img.getWidth();
int height = img.getHeight();
int newWidth = 100;
int newHeight = height * newWidth / width;
Image scaledImage = img.getScaledInstance(newWidth, newHeight, Image.SCALE_SMOOTH);
BufferedImage thumbnail = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = thumbnail.createGraphics();
g2d.drawImage(scaledImage, 0, 0, null);
g2d.dispose();
String thumbnailName = UUID.randomUUID().toString() + ".jpg";
File thumbnailFile = new File("path/to/thumbnails/" + thumbnailName);
ImageIO.write(thumbnail, "jpg", thumbnailFile);
model.addAttribute("thumbnail", "/thumbnails/" + thumbnailName);
return "result";
}
}
- 添加前端页面。
<!DOCTYPE html>
<html>
<head>
<title>文件上传示例</title>
</head>
<body>
<h1>文件上传示例</h1>
<form action="/upload" method="POST" enctype="multipart/form-data">
<input type="file" name="file">
<button type="submit">提交</button>
</form>
<hr>
<img src="${thumbnail}" alt="缩略图">
</body>
</html>
示例二:使用Apache Commons FileUpload实现文件上传
- 在pom.xml中添加依赖。
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.4</version>
</dependency>
- 添加上传文件的Servlet。
@WebServlet(name = "FileUploadServlet", urlPatterns = {"/upload"})
@MultipartConfig
public class FileUploadServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
try {
List<FileItem> items = upload.parseRequest(request);
Iterator<FileItem> iter = items.iterator();
while (iter.hasNext()) {
FileItem item = iter.next();
if (!item.isFormField() && StringUtils.isNotBlank(item.getName())) {
String originalFilename = item.getName();
String extension = FileUtils.getFileExtension(originalFilename);
String newName = UUID.randomUUID().toString() + "." + extension;
File newFile = new File("path/to/uploaded/" + newName);
item.write(newFile);
BufferedImage img = ImageIO.read(newFile);
int width = img.getWidth();
int height = img.getHeight();
int newWidth = 100;
int newHeight = height * newWidth / width;
Image scaledImage = img.getScaledInstance(newWidth, newHeight, Image.SCALE_SMOOTH);
BufferedImage thumbnail = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = thumbnail.createGraphics();
g2d.drawImage(scaledImage, 0, 0, null);
g2d.dispose();
String thumbnailName = UUID.randomUUID().toString() + ".jpg";
File thumbnailFile = new File("path/to/thumbnails/" + thumbnailName);
ImageIO.write(thumbnail, "jpg", thumbnailFile);
response.setContentType("text/html;charset=UTF-8");
response.getWriter().write("/thumbnails/" + thumbnailName);
}
}
} catch (Exception ex) {
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
response.getWriter().write(ex.getMessage());
}
}
}
- 添加前端页面。
<!DOCTYPE html>
<html>
<head>
<title>文件上传示例</title>
</head>
<body>
<h1>文件上传示例</h1>
<form action="/upload" method="POST" enctype="multipart/form-data">
<input type="file" name="file">
<button type="submit">提交</button>
</form>
<hr>
<img id="thumbnail" src="" alt="缩略图" style="display: none">
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.slim.min.js"></script>
<script>
$(function () {
$('form').submit(function (event) {
event.preventDefault();
var formData = new FormData(this);
$.ajax({
url: '/upload',
type: 'POST',
data: formData,
processData: false,
contentType: false,
success: function (data) {
$('#thumbnail').attr('src', data);
$('#thumbnail').show();
},
error: function (jqXHR, textStatus, errorThrown) {
alert('上传失败:' + errorThrown);
}
});
});
});
</script>
</body>
</html>
以上就是“Java实战之实现文件资料上传并生成缩略图”的完整攻略,希望能够对你有所帮助。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:Java实战之实现文件资料上传并生成缩略图 - Python技术站