阿超
>
jquery和springBoot文件上传
友情在过去的生活里,就像一盏明灯,照彻了我的灵魂,使我的生存有了一点点光彩。——巴金
首先是后端代码:
写入文件工具类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
| package com.ruben.simplescaffold.utils;
import lombok.extern.slf4j.Slf4j;
import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.Collections; import java.util.Optional; import java.util.Spliterator; import java.util.function.Predicate; import java.util.stream.Stream;
@Slf4j public class FileUtils {
private FileUtils() { }
public static Boolean saveFile(byte[] file, String filePath, String fileName) { File targetFile = new File(filePath); Predicate.isEqual(Optional.of(targetFile).map(File::exists).filter(Boolean.TRUE::equals).orElseGet(targetFile::mkdirs)).and(i -> Stream.builder().add(null).build().spliterator().tryAdvance(c -> log.error("mkdir failed"))).test(false); String fullPath = filePath + fileName; try (FileOutputStream out = new FileOutputStream(fullPath)) { out.write(file); out.flush(); return Stream.builder().add(fullPath).add(out).build().spliterator().tryAdvance(i -> log.info("file path is:{}", i)); } catch (IOException e) { Spliterator<IOException> spliterator = Collections.singleton(e).spliterator(); spliterator.tryAdvance(c -> log.error("file save failed!", c)); return spliterator.tryAdvance(c -> log.error("Oh!You found me!", c)); } }
}
|
然后是Controller
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
| package com.ruben.simplescaffold.controller;
import com.baomidou.mybatisplus.core.toolkit.ClassUtils; import com.baomidou.mybatisplus.core.toolkit.IdWorker; import com.ruben.simplescaffold.pojo.common.Result; import com.ruben.simplescaffold.utils.FileUtils; import com.ruben.simplescaffold.utils.Opt; import lombok.extern.slf4j.Slf4j; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile;
import java.util.Objects;
@Slf4j @RestController public class UploadController {
@PostMapping("upload") public Result projectPictureUpload(MultipartFile file) { if (file.isEmpty()) { return Result.error("项目图片不能为空"); } String originalFilename = Opt.ofNullable(file.getOriginalFilename()).orElseGet(file::getName); String suffix = originalFilename.substring(originalFilename.lastIndexOf(".") + 1); String fileName = IdWorker.getTimeId() + "." + suffix; String filePath = ""; filePath = Objects.requireNonNull(ClassUtils.getDefaultClassLoader().getResource("static")).getPath() + "/upload/img/"; try { Boolean writePictureTarget = FileUtils.saveFile(file.getBytes(), filePath, fileName); Boolean writePictureProject = FileUtils.saveFile(file.getBytes(), System.getProperty("user.dir") + "/src/main/resources/static/upload/img/", fileName); if (!writePictureTarget) { return Result.error("上传项目文件失败"); } String fullImgPath = "/upload/img/" + fileName; return Result.ok().data(fullImgPath); } catch (Exception e) { log.error("上传项目文件失败", e); return Result.error("上传项目文件失败"); } } }
|
这里用到的Result
在之前一篇博客提到过,当然也可以在最下方找到全部的源码
然后就是前端代码啦
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>上传Demo</title> <script src="https://www.jq22.com/jquery/jquery-3.3.1.js"></script> </head> <body> <div> <input type="file" onchange="upload(this)"> </div> <script> function upload(file) { file = $(file) if (!file.prop("files")[0]) { return } let formData = new FormData() formData.append('file', file.prop("files")[0]); $.ajax({ type: "post", url: "/upload", data: formData, processData: false, contentType: false, success: function (res) { file.after(`<img src='${res.data}'>`) } } ); } </script> </body> </html>
|
效果如下:
完整源码:https://gitee.com/VampireAchao/simple-scaffold.git