spring boot +Vue + element-ui实现图片上传和回显

对于图片上传和显示后台采用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> 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  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:

 
            
点击上传
取 消 确 定

图片上传:

  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('新增图书失败!')
                    }
                })
            },

图片的显示:

 
           
        

你可能感兴趣的:(vue.js,spring,boot,前端)