当前位置:   article > 正文

Java Web 实现文件上传和下载接口功能_java post请求下载文件

java post请求下载文件

1.上传java代码实现

  1. @ResponseBody
  2. @PostMapping("/upload")
  3. public ResponseVo upload(@RequestParam(value = "file", required = false) MultipartFile multipartFile) {
  4. File file=new File("上传到服务器的文件地址");
  5. try {
  6. FileUtil.copy(multipartFile.getBytes(), file);
  7. } catch (IOException e) {
  8. return ResultUtil.error();
  9. }
  10. return ResultUtil.success();
  11. }

上传用post或者get请求都可以,这里代码中用post做的示例。

2.文件流下载java代码实现

文件下载除了静态访问(及nginx、tomcat等服务器映射到后的文件web路径)下载以外 ,还可以通过流的方式下载,代码如下:

  1. /**
  2. * 下载
  3. */
  4. @PostMapping("/download")
  5. public void download(String fileName, HttpServletResponse response) throws IOException {
  6. FileInputStream fis=new FileInputStream("服务器文件所在路径");
  7. response.addHeader("Content-Disposition", "attachment;filename="+fileName+";"+"filename*=utf-8''"+fileName);
  8. FileUtil.copy(fis, response.getOutputStream());
  9. }

上传用post或者get请求都可以,这里代码中用post做的示例。

3.Fileutil工具类代码:

  1. import com.tarzan.navigation.common.exception.ForbiddenException;
  2. import lombok.extern.slf4j.Slf4j;
  3. import org.apache.commons.lang3.StringUtils;
  4. import org.springframework.lang.NonNull;
  5. import org.springframework.util.Assert;
  6. import org.springframework.util.StreamUtils;
  7. import java.io.*;
  8. import java.nio.file.*;
  9. import java.nio.file.attribute.BasicFileAttributes;
  10. import java.util.Arrays;
  11. import java.util.List;
  12. import java.util.Objects;
  13. import java.util.stream.Collectors;
  14. import java.util.stream.Stream;
  15. import java.util.zip.ZipEntry;
  16. import java.util.zip.ZipInputStream;
  17. import java.util.zip.ZipOutputStream;
  18. @Slf4j
  19. public class FileUtil {
  20. /**
  21. * Copies folder.
  22. *
  23. * @param source source path must not be null
  24. * @param target target path must not be null
  25. */
  26. public static void copyFolder(@NonNull Path source, @NonNull Path target) throws IOException {
  27. Assert.notNull(source, "Source path must not be null");
  28. Assert.notNull(target, "Target path must not be null");
  29. Files.walkFileTree(source, new SimpleFileVisitor<Path>() {
  30. @Override
  31. public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
  32. throws IOException {
  33. Path current = target.resolve(source.relativize(dir).toString());
  34. Files.createDirectories(current);
  35. return FileVisitResult.CONTINUE;
  36. }
  37. @Override
  38. public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
  39. throws IOException {
  40. Files.copy(file, target.resolve(source.relativize(file).toString()),
  41. StandardCopyOption.REPLACE_EXISTING);
  42. return FileVisitResult.CONTINUE;
  43. }
  44. });
  45. }
  46. /**
  47. * Deletes folder recursively.
  48. *
  49. * @param deletingPath deleting path must not be null
  50. */
  51. public static void deleteFolder(@NonNull Path deletingPath) {
  52. Assert.notNull(deletingPath, "Deleting path must not be null");
  53. if (Files.notExists(deletingPath)) {
  54. return;
  55. }
  56. log.info("Deleting [{}]", deletingPath);
  57. delete(deletingPath.toFile());
  58. log.info("Deleted [{}] successfully", deletingPath);
  59. }
  60. private static void delete(File file) {
  61. if(file.isDirectory()){
  62. Arrays.asList(Objects.requireNonNull(file.listFiles())).forEach(FileUtil::delete);
  63. }
  64. file.delete();
  65. }
  66. /**
  67. * Renames file or folder.
  68. *
  69. * @param pathToRename file path to rename must not be null
  70. * @param newName new name must not be null
  71. */
  72. public static void rename(@NonNull Path pathToRename, @NonNull String newName)
  73. throws IOException {
  74. Assert.notNull(pathToRename, "File path to rename must not be null");
  75. Assert.notNull(newName, "New name must not be null");
  76. Path newPath = pathToRename.resolveSibling(newName);
  77. log.info("Rename [{}] to [{}]", pathToRename, newPath);
  78. Files.move(pathToRename, newPath);
  79. log.info("Rename [{}] successfully", pathToRename);
  80. }
  81. /**
  82. * Unzips content to the target path.
  83. *
  84. * @param zis zip input stream must not be null
  85. * @param targetPath target path must not be null and not empty
  86. * @throws IOException throws when failed to access file to be unzipped
  87. */
  88. public static void unzip(@NonNull ZipInputStream zis, @NonNull Path targetPath)
  89. throws IOException {
  90. // 1. unzip file to folder
  91. // 2. return the folder path
  92. Assert.notNull(zis, "Zip input stream must not be null");
  93. Assert.notNull(targetPath, "Target path must not be null");
  94. // Create path if absent
  95. createIfAbsent(targetPath);
  96. // Folder must be empty
  97. ensureEmpty(targetPath);
  98. ZipEntry zipEntry = zis.getNextEntry();
  99. while (zipEntry != null) {
  100. // Resolve the entry path
  101. Path entryPath = targetPath.resolve(zipEntry.getName());
  102. // Check directory
  103. checkDirectoryTraversal(targetPath, entryPath);
  104. if (zipEntry.isDirectory()) {
  105. // Create directories
  106. Files.createDirectories(entryPath);
  107. } else {
  108. // Copy file
  109. Files.copy(zis, entryPath);
  110. }
  111. zipEntry = zis.getNextEntry();
  112. }
  113. }
  114. /**
  115. * Unzips content to the target path.
  116. *
  117. * @param bytes zip bytes array must not be null
  118. * @param targetPath target path must not be null and not empty
  119. * @throws IOException io exception
  120. */
  121. public static void unzip(@NonNull byte[] bytes, @NonNull Path targetPath) throws IOException {
  122. Assert.notNull(bytes, "Zip bytes must not be null");
  123. ZipInputStream zis = new ZipInputStream(new ByteArrayInputStream(bytes));
  124. unzip(zis, targetPath);
  125. }
  126. /**
  127. * Zips folder or file.
  128. *
  129. * @param pathToZip file path to zip must not be null
  130. * @param pathOfArchive zip file path to archive must not be null
  131. * @throws IOException throws when failed to access file to be zipped
  132. */
  133. public static void zip(@NonNull Path pathToZip, @NonNull Path pathOfArchive)
  134. throws IOException {
  135. try (OutputStream outputStream = Files.newOutputStream(pathOfArchive)) {
  136. try (ZipOutputStream zipOut = new ZipOutputStream(outputStream)) {
  137. zip(pathToZip, zipOut);
  138. }
  139. }
  140. }
  141. /**
  142. * Zips folder or file.
  143. *
  144. * @param pathToZip file path to zip must not be null
  145. * @param zipOut zip output stream must not be null
  146. * @throws IOException throws when failed to access file to be zipped
  147. */
  148. public static void zip(@NonNull Path pathToZip, @NonNull ZipOutputStream zipOut)
  149. throws IOException {
  150. // Zip file
  151. zip(pathToZip, pathToZip.getFileName().toString(), zipOut);
  152. }
  153. /**
  154. * Zips folder or file.
  155. *
  156. * @param fileToZip file path to zip must not be null
  157. * @param fileName file name must not be blank
  158. * @param zipOut zip output stream must not be null
  159. * @throws IOException throws when failed to access file to be zipped
  160. */
  161. private static void zip(@NonNull Path fileToZip, @NonNull String fileName,
  162. @NonNull ZipOutputStream zipOut) throws IOException {
  163. if (Files.isDirectory(fileToZip)) {
  164. log.debug("Try to zip folder: [{}]", fileToZip);
  165. // Append with '/' if missing
  166. String folderName =
  167. StringUtils.appendIfMissing(fileName, File.separator, File.separator);
  168. // Create zip entry and put into zip output stream
  169. zipOut.putNextEntry(new ZipEntry(folderName));
  170. // Close entry for writing the next entry
  171. zipOut.closeEntry();
  172. // Iterate the sub files recursively
  173. try (Stream<Path> subPathStream = Files.list(fileToZip)) {
  174. // There should not use foreach for stream as internal zip method will throw
  175. // IOException
  176. List<Path> subFiles = subPathStream.collect(Collectors.toList());
  177. for (Path subFileToZip : subFiles) {
  178. // Zip children
  179. zip(subFileToZip, folderName + subFileToZip.getFileName(), zipOut);
  180. }
  181. }
  182. } else {
  183. // Open file to be zipped
  184. // Create zip entry for target file
  185. ZipEntry zipEntry = new ZipEntry(fileName);
  186. // Put the entry into zip output stream
  187. zipOut.putNextEntry(zipEntry);
  188. // Copy file to zip output stream
  189. Files.copy(fileToZip, zipOut);
  190. // Close entry
  191. zipOut.closeEntry();
  192. }
  193. }
  194. /**
  195. * Creates directories if absent.
  196. *
  197. * @param path path must not be null
  198. * @throws IOException io exception
  199. */
  200. public static void createIfAbsent(@NonNull Path path) throws IOException {
  201. Assert.notNull(path, "Path must not be null");
  202. if (Files.notExists(path)) {
  203. // Create directories
  204. Files.createDirectories(path);
  205. log.debug("Created directory: [{}]", path);
  206. }
  207. }
  208. /**
  209. * The given path must be empty.
  210. *
  211. * @param path path must not be null
  212. * @throws IOException io exception
  213. */
  214. public static void ensureEmpty(@NonNull Path path) throws IOException {
  215. if (!isEmpty(path)) {
  216. throw new DirectoryNotEmptyException("Target directory: " + path + " was not empty");
  217. }
  218. }
  219. /**
  220. * Checks directory traversal vulnerability.
  221. *
  222. * @param parentPath parent path must not be null.
  223. * @param pathToCheck path to check must not be null
  224. */
  225. public static void checkDirectoryTraversal(@NonNull String parentPath,
  226. @NonNull String pathToCheck) {
  227. checkDirectoryTraversal(Paths.get(parentPath), Paths.get(pathToCheck));
  228. }
  229. /**
  230. * Checks directory traversal vulnerability.
  231. *
  232. * @param parentPath parent path must not be null.
  233. * @param pathToCheck path to check must not be null
  234. */
  235. public static void checkDirectoryTraversal(@NonNull Path parentPath,
  236. @NonNull String pathToCheck) {
  237. checkDirectoryTraversal(parentPath, Paths.get(pathToCheck));
  238. }
  239. /**
  240. * Checks directory traversal vulnerability.
  241. *
  242. * @param parentPath parent path must not be null.
  243. * @param pathToCheck path to check must not be null
  244. */
  245. public static void checkDirectoryTraversal(@NonNull Path parentPath,
  246. @NonNull Path pathToCheck) {
  247. Assert.notNull(parentPath, "Parent path must not be null");
  248. Assert.notNull(pathToCheck, "Path to check must not be null");
  249. if (pathToCheck.normalize().startsWith(parentPath)) {
  250. return;
  251. }
  252. throw new ForbiddenException("你没有权限访问 " + pathToCheck);
  253. }
  254. /**
  255. * Checks if the given path is empty.
  256. *
  257. * @param path path must not be null
  258. * @return true if the given path is empty; false otherwise
  259. * @throws IOException io exception
  260. */
  261. public static boolean isEmpty(@NonNull Path path) throws IOException {
  262. Assert.notNull(path, "Path must not be null");
  263. if (!Files.isDirectory(path) || Files.notExists(path)) {
  264. return true;
  265. }
  266. try (Stream<Path> pathStream = Files.list(path)) {
  267. return !pathStream.findAny().isPresent();
  268. }
  269. }
  270. /**
  271. * Copy the contents of the given input File to the given output File.
  272. * @param in the file to copy from
  273. * @param out the file to copy to
  274. * @return the number of bytes copied
  275. * @throws IOException in case of I/O errors
  276. */
  277. public static int copy(File in, File out) throws IOException {
  278. Assert.notNull(in, "No input File specified");
  279. Assert.notNull(out, "No output File specified");
  280. return copy(Files.newInputStream(in.toPath()), Files.newOutputStream(out.toPath()));
  281. }
  282. /**
  283. * Copy the contents of the given byte array to the given output File.
  284. * @param in the byte array to copy from
  285. * @param out the file to copy to
  286. * @throws IOException in case of I/O errors
  287. */
  288. public static void copy(byte[] in, File out) throws IOException {
  289. Assert.notNull(in, "No input byte array specified");
  290. Assert.notNull(out, "No output File specified");
  291. copy(new ByteArrayInputStream(in), Files.newOutputStream(out.toPath()));
  292. }
  293. /**
  294. * Copy the contents of the given InputStream to the given OutputStream.
  295. * Closes both streams when done.
  296. * @param in the stream to copy from
  297. * @param out the stream to copy to
  298. * @return the number of bytes copied
  299. * @throws IOException in case of I/O errors
  300. */
  301. public static int copy(InputStream in, OutputStream out) throws IOException {
  302. Assert.notNull(in, "No InputStream specified");
  303. Assert.notNull(out, "No OutputStream specified");
  304. try {
  305. return StreamUtils.copy(in, out);
  306. }
  307. finally {
  308. try {
  309. in.close();
  310. }
  311. catch (IOException ex) {
  312. }
  313. try {
  314. out.close();
  315. }
  316. catch (IOException ex) {
  317. }
  318. }
  319. }
  320. /**
  321. * Copy the contents of the given byte array to the given OutputStream.
  322. * Closes the stream when done.
  323. * @param in the byte array to copy from
  324. * @param out the OutputStream to copy to
  325. * @throws IOException in case of I/O errors
  326. */
  327. public static void copy(byte[] in, OutputStream out) throws IOException {
  328. Assert.notNull(in, "No input byte array specified");
  329. Assert.notNull(out, "No OutputStream specified");
  330. try {
  331. out.write(in);
  332. }
  333. finally {
  334. try {
  335. out.close();
  336. }
  337. catch (IOException ex) {
  338. }
  339. }
  340. }
  341. }

 ForbiddenException 访问权限异常类

  1. import org.springframework.http.HttpStatus;
  2. /**
  3. * Exception caused by accessing forbidden resources.
  4. *
  5. * @author johnniang
  6. */
  7. public class ForbiddenException extends RuntimeException {
  8. public ForbiddenException() {
  9. super();
  10. }
  11. public ForbiddenException(String message) {
  12. super(message);
  13. }
  14. public ForbiddenException(String message, Throwable cause) {
  15. super(message, cause);
  16. }
  17. public HttpStatus getStatus() {
  18. return HttpStatus.FORBIDDEN;
  19. }
  20. }

图片示例

 

完整代码请参考:

tarzan-navigation: 泰山导航网站-java版

4.相关知识

MultipartFile、HttpServletResponse和FileInputStream都是在Java Web开发中常用的类。它们分别用于处理上传文件、响应HTTP请求和读取文件内容。下面将详细解释这三个类的特点和用法。

MultipartFile:


MultipartFile是Spring框架提供的接口,用于处理上传的文件数据。它提供了一组方法来获取文件名、文件类型、文件大小以及文件内容等信息。

以下是MultipartFile接口中常用的方法:

  • getOriginalFilename():获取上传文件的原始文件名。
  • getContentType():获取上传文件的内容类型。
  • getSize():获取上传文件的大小。
  • getBytes():获取上传文件的字节数组。
  • getInputStream():获取上传文件的输入流。

HttpServletResponse:


HttpServletResponse是Java Servlet API提供的接口,用于向客户端发送HTTP响应。通过HttpServletResponse,我们可以设置响应的状态码、头部信息和内容等。

以下是HttpServletResponse接口中常用的方法:

  • setStatus(int sc):设置HTTP响应的状态码。
  • setHeader(String name, String value):设置HTTP响应的头部信息。
  • getWriter():获取输出流,用于将数据写入响应体。

FileInputStream:


FileInputStream是Java IO提供的类,用于读取文件内容。它继承自InputStream,可以打开一个文件并从中读取字节数据。

以下是FileInputStream类常用的方法:

  • read():读取单个字节的数据。
  • read(byte[] b):将最多b.length个字节的数据读入到字节数组b中。
  • close():关闭输入流。

总结:


MultipartFile用于处理上传的文件数据,HttpServletResponse用于向客户端发送HTTP响应,FileInputStream用于读取文件内容。它们在Java Web开发中起着重要的作用,能够处理文件上传、下载和读取等常见任务。希望以上内容对您有所帮助,如有任何疑问,请随时提问。

本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号