Java实现文件上传
1. 准备工作
在进行文件上传前,需要在服务器上建立一个存储上传文件的目录,并且需要在前端用HTML5的file标签来设置文件选择框。
2. 前端代码
前端代码使用HTML5的form表单和一个file选择框,具体如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>文件上传示例</title>
</head>
<body>
<form action="/file/uploadFile" method="post" enctype="multipart/form-data">
<label for="file">选择要上传的文件:</label>
<input type="file" name="file" id="file"><br>
<input type="submit" name="submit" value="上传">
</form>
</body>
</html>
3. 后端代码
后端代码中使用Spring MVC框架来处理文件上传,controller代码实现如下:
@Controller
@RequestMapping("/file")
public class FileUploadController {
@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
public String uploadFileHandler(@RequestParam("file") MultipartFile file, ModelMap model) {
if (!file.isEmpty()) {
try {
String fileName = file.getOriginalFilename();
byte[] bytes = file.getBytes();
// TODO 存储上传文件并且返回下载链接
model.addAttribute("message", "上传文件成功:" + fileName);
return "success";
} catch (Exception e) {
model.addAttribute("message", "上传文件失败:" + e.getMessage());
return "error";
}
} else {
model.addAttribute("message", "请选择要上传的文件!");
return "error";
}
}
}
Java实现文件下载
1. 前端代码
文件下载的前端代码可以通过超链接或者一个表单的submit方式来实现,直接下载不需要前端ajax方式。
2. 后端代码
文件下载的后端代码中,需要设置Response的头文件,告诉浏览器要下载的文件的信息,具体实现如下:
@Controller
@RequestMapping("/file")
public class FileDownloadController {
@RequestMapping(value = "/downloadFile/{file_name:.+}", method = RequestMethod.GET)
public void downloadFile(@PathVariable("file_name") String fileName, HttpServletResponse response) {
try {
File file = new File("存储文件的路径" + fileName);
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment; filename=\"" + file.getName() + "\"");
InputStream inputStream = new FileInputStream(file);
OutputStream outputStream = response.getOutputStream();
byte[] buffer = new byte[4096];
int length;
while ((length = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, length);
}
outputStream.flush();
outputStream.close();
inputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Java实现图片压缩
1. 使用Java自带类库压缩图片
Java自带了图片处理类库,可以使用Java提供的类库来实现图片压缩,具体实现如下:
public static void compressImageByJava(File sourceFile, File targetFile, int targetWidth, int targetHeight, float quality) {
FileInputStream inputStream;
try {
inputStream = new FileInputStream(sourceFile);
Image img = ImageIO.read(inputStream);
int width = img.getWidth(null);
int height = img.getHeight(null);
if (width > targetWidth) {
height = height * targetWidth / width;
width = targetWidth;
}
if (height > targetHeight) {
width = width * targetHeight / height;
height = targetHeight;
}
BufferedImage targetImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D graphics = targetImage.createGraphics();
graphics.drawImage(img, 0, 0, width, height, null);
graphics.dispose();
FileOutputStream out = new FileOutputStream(targetFile);
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(targetImage);
param.setQuality(quality, true);
encoder.encode(targetImage, param);
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
2. 使用第三方类库压缩图片
如果想要更灵活的图片压缩方式,可以使用第三方类库ImageIO和Thumbnails来实现,具体实现如下:
public static void compressImageByThirdParty(File sourceFile, File targetFile, int targetWidth, int targetHeight, float quality) {
try {
Thumbnails.of(sourceFile)
.size(targetWidth, targetHeight)
.outputQuality(quality) // 设置图片质量
.toFile(targetFile);
} catch (Exception e) {
e.printStackTrace();
}
}
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:java实现文件上传下载和图片压缩代码示例 - Python技术站