赞
踩
对于图片上传和显示后台采用SpringBoot实现:
- package com.example.demo.controller;
-
- import cn.hutool.core.io.FileUtil;
- import cn.hutool.core.util.IdUtil;
- import com.example.demo.domain.Books;
- import com.example.demo.service.BooksService;
- import com.example.demo.util.Result;
- import io.swagger.annotations.ApiOperation;
- import org.springframework.beans.factory.annotation.Value;
- import org.springframework.web.bind.annotation.*;
- import org.springframework.web.multipart.MultipartFile;
-
- import javax.annotation.Resource;
- import javax.servlet.http.HttpServletResponse;
- import java.io.File;
- import java.io.IOException;
- import java.io.OutputStream;
- import java.io.UnsupportedEncodingException;
- import java.net.URLEncoder;
- import java.util.Arrays;
- import java.util.List;
-
- @RestController
- @RequestMapping("/books")
- public class BookController {
-
- @Value("${server.port}")
- private String port;
-
- String path=System.getProperty("user.dir") +"/book-java/src/main/resources/upload/";
- private static final String host="http://localhost";
-
- @Resource
- private BooksService booksService;
-
- @ApiOperation("图书列表")
- @GetMapping("/")
- public Result<List<Books>> findBooks(){
- return new Result<>(true, 200, "OK", this.booksService.list());
- }
-
- @ApiOperation("新增图书")
- @PostMapping("/add")
- public Result<?> addBook(@RequestBody Books books){
- return this.booksService.save(books)
- ? new Result<>(true, 200, "新增成功!")
- : new Result<>(false, 202, "新增失败!");
- }
-
- @ApiOperation("上传图片")
- @PostMapping("/upload")
- public Result<?> upload(MultipartFile file){
-
- System.out.println(path);
- String id= IdUtil.fastSimpleUUID();
- String originalFilename = file.getOriginalFilename();
- String imgPath= path+id+"_"+originalFilename;
- System.out.println(imgPath);
- try {
- FileUtil.writeBytes(file.getBytes(),imgPath);
- } catch (IOException e) {
- e.printStackTrace();
- return new Result<>(false, 303, "上传失败!");
- }
- return new Result<>(true, 200, "上传成功", host+":"+this.port+"/books/"+id);
- }
-
- @GetMapping("/{flag}")
- @ApiOperation("文件下载")
- public void downFile(@PathVariable String flag, HttpServletResponse response){
- OutputStream outputStream=null;
- File file=new File(path);
- List<String> list= Arrays.asList(file.list());
- String fileName=list.stream().filter(name->name.contains(flag)).findAny().orElse("");
- if(fileName!=null && !fileName.isEmpty()){
- try {
- response.addHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(fileName, "utf-8"));
- response.setContentType("application/octet-stream");
-
- byte[] arr= FileUtil.readBytes(path+fileName);
- outputStream=response.getOutputStream();
- outputStream.write(arr);
- outputStream.flush();
- outputStream.close();
- } catch (UnsupportedEncodingException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- }

这里要特别注意的是:参数名称必须是file,必须是post方式!
public Result<?> upload(MultipartFile file){
前端Vue:
- <el-dialog
- title="添加图书"
- :visible.sync="dialogVisible"
- width="30%"
- :before-close="handleClose">
- <div>
- <el-form :model="book" label-width="120px">
- <el-form-item label="图书名称">
- <el-input v-model="book.title"></el-input>
- </el-form-item>
- <el-form-item label="图书作者">
- <el-input v-model="book.author"></el-input>
- </el-form-item>
- <el-form-item label="图书价格">
- <el-input v-model="book.price"></el-input>
- </el-form-item>
- <el-form-item label="库存数量">
- <el-input v-model="book.kucun"></el-input>
- </el-form-item>
- <el-form-item label="图书封面">
- <el-upload
- class="upload-demo"
- v-model="book.pic"
- action="http://localhost:8081/books/upload" :on-success="upPic">
- <el-button size="small" type="primary">点击上传</el-button>
- </el-upload>
- </el-form-item>
-
- </el-form>
- </div>
- <span slot="footer" class="dialog-footer">
- <el-button @click="dialogVisible = false">取 消</el-button>
- <el-button type="primary" @click="addBook">确 定</el-button>
- </span>
- </el-dialog>

图片上传:
- upPic(resp){
- console.log(resp.data);
- //获取图片名称
- this.book.pic=resp.data;
- },
新增:
- addBook(){
- request.post('/books/add',this.book).then(resp=>{
- if(resp.code===200){
- this.$message.success('新增图书成功!');
- this.book={};
- this.getBooks();
- this.dialogVisible=false;
-
- }else{
- this.$message.error('新增图书失败!')
- }
- })
- },
图片的显示:
- <el-table-column
- label="封面"
- >
- <template #default="scope">
- <el-image
- style="width: 50px; height: 50px"
- :src="scope.row.pic"
- :preview-src-list="[scope.row.pic]">
- </el-image>
- </template>
- </el-table-column>
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。