0
点赞
收藏
分享

微信扫一扫

vue和java图片上传

<font color=#999AAA >

</font>

@[TOC](文章目录

<hr style=" border:solid; width:100px; height:1px;" color=#000000 size=1">

前言

<font color=#999AAA >
</font>

<hr style=" border:solid; width:100px; height:1px;" color=#000000 size=1">

1、流程及图

在这里插入图片描述

2、前端:

1.表单提交

                    <!-- 企业简称 -->
                <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="800px">
                    <el-form :model="editEntity" ref="editEntity"
                             label-width="80px"  class="demo-ruleForm" >
                        <el-row>
                            <el-col :span="2">
                                &nbsp;
                            </el-col>
                            <el-col :span="12">
                                &nbsp;&nbsp;&nbsp;
                            <el-button type="danger" disabled>{{editEntity.compayName}}</el-button>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col :span="12">
                                <el-form-item label="企业名称" prop="name">
                                    <el-input type="text" placeholder="请输入企业名称,最多输入十个字"
                                              v-model="editEntity.name"></el-input>
                                </el-form-item>
                            </el-col>

                            <el-col :span="12">
                                <el-form-item label="A类单位" prop="invoiceCompanyidA">
                                    <el-select size="mini" v-model="editEntity.invoiceCompanyidA" >
                                        <el-option v-for="invoiceCompanyItem in invoiceCompanyOptionsA" :key="invoiceCompanyItem.id"
                                                   :label="invoiceCompanyItem.name" :value="invoiceCompanyItem.id"></el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row>

                            <el-col :span="12">
                                <el-form-item label="A类公章" prop="taxImageUrl">
                                    <el-upload class="avatar-uploader" :action="uploadImageUrl"
                                               :multiple="false" accept="image/*" :limit="1024" :auto-upload="true"
                                               :show-file-list="false" :on-success="handleUploadSuccess1">
                                        <img v-if="editEntity.taxImageUrl"
                                             :src="editEntity.taxImageUrl" class="avatar">
                                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                                    </el-upload>
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </el-form>
                    <div slot="footer" class="dialog-footer">
                        <el-button type="primary" @click="save()">确定</el-button>
                        <el-button @click="dialogVisible = false">取消</el-button>
                    </div>

                </el-dialog>

2.上传图片及相关方法

            handleUploadSuccess: function (res) {// 处理上传成功事件
                if (res.success) {// 成功
                    this.editAbbreviationFormEntity.imageUrl = res.data;
                } else {// 失败
                    this.$message.error(res.message);
                }
            },

3、配置文件application.xml

    <!-- 本地文件服务 -->
    <bean class="com.cherry.framework.service.impl.LocalFileServiceImpl">
        <property name="fileServerSavepath" value="${file_server_savepath}" />
        <property name="fileServerHttppath" value="${file_server_httppath}" />
    </bean>

3、后端

1.控制器

    /**
     * 文件目录:图片目录
     */
    public static final String FILE_DIR_CACHET = "cachet";

    /**
     * 上传图片
     * @param file
     * @return
     */
    @RequestMapping("/uploadImage")
    @ResponseBody
    public Result uploadImage(MultipartFile file){
        return  fileService.uploadFile(file, Constants.FILE_DIR_CACHET);
    }
2.上传接口

    private String fileServerSavepath;

    private String fileServerHttppath;

    public String getFileServerSavepath() {
        return fileServerSavepath;
    }

    public void setFileServerSavepath(String fileServerSavepath) {
        this.fileServerSavepath = fileServerSavepath;
    }

    public String getFileServerHttppath() {
        return fileServerHttppath;
    }

    public void setFileServerHttppath(String fileServerHttppath) {
        this.fileServerHttppath = fileServerHttppath;
    }

    /**
     * 上传到本地服务器
     */
    public Result uploadFile(MultipartFile file, String dirName) {
        String filePath = dirName + "/" + UUID.randomUUID().toString();
        try {
            File dest = new File(fileServerSavepath, filePath);
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();
            }
            file.transferTo(dest);
        } catch (IllegalStateException | IOException e) {
            String errorMsg = "上传文件[" + file.getOriginalFilename() + "]失败!";
            logger.error(errorMsg, e);
            return Results.uploadError();
        }
        return Results.uploadOk(fileServerHttppath + filePath);
    }

    /**
     * 上传到七牛云
     */
    public Result uploadFileQiniu(MultipartFile file) {
    String uuid = UUID.randomUUID().toString();
    InputStream is = null;
    try {
        is = file.getInputStream();
        String imgUrl = QiniuUpload.uploadFile(is , uuid);
        return Results.uploadOk(imgUrl);
    }catch (Exception e){
        e.printStackTrace();
    }finally {
        try {
            if (is != null) {
                is.close();
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
    }
    return Results.error();
}

    /**
     * 按指定大小压缩后上传到七牛云
     */
    public Result uploadImageResize(MultipartFile file, String dirName, double destFileSize) {
        String uuid = UUID.randomUUID().toString();
        String filePath = dirName + "/" + uuid;
        try {
            File dest = new File(fileServerSavepath, filePath);
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();
            }
            file.transferTo(dest);
            if((Double.isNaN(destFileSize)) || "".equals(destFileSize)){
                destFileSize = 15.0;
            }
            String imgUrl = QiniuUpload.uploadFile(ImageUtil.commpressImageRatio(dest,destFileSize), uuid);
            return Results.uploadOk(imgUrl);
        } catch (IllegalStateException | IOException e) {
            String errorMsg = "上传文件[" + file.getOriginalFilename() + "]失败!";
            logger.error(errorMsg, e);
            return Results.uploadError();
        }
    }
3.七牛云上传
   /**
     * 上传文件到七牛云(文件流)
     * @param is 文件流
     * @param key 文件名称
     * @return 云文件访问路径
     */
    public static String uploadFile(InputStream is, String key){
        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(qiniuConfig.getRegion());
        UploadManager uploadManager = new UploadManager(cfg);
        try {
            Response response = uploadManager.put(is, key, getAccessToken(), null, null);
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            return qiniuConfig.getCdnPath() + putRet.key;
        } catch (QiniuException ex) {
            ex.printStackTrace();
        }
        return null;
    }
4.递归压缩图片

    /**
     * 按尺寸、精度及其他条件比例缩放
     * @param file
     * @param destFileSize 指定图片大小(单位:kb)
     * @throws IOException
     */
    public static InputStream commpressImageRatio(File file,double destFileSize) throws IOException {
        final int byteLenght = 1024; // 字节长度
        final double minRatio = 0.9; // 压缩比率
        double ratio = destFileSize/((double) file.length()/byteLenght);
        if(ratio >= minRatio){
            return new FileInputStream(file);
        }else {
            Thumbnails.of(file).scale(0.9).outputQuality(0.9).outputFormat("jpg").toFile(file);
            String path = file.getAbsolutePath();
            int i = path.lastIndexOf(".")+1;
            String suffix  = path.substring(i);
            if(!suffix.equals("jpg")){
                file = new File(file.getAbsolutePath()+".jpg");
                File file1 = new File(path);
                file1.delete();
            }
            double ratio1 =  destFileSize/((double) file.length()/byteLenght);
            if(ratio1 < minRatio){
                commpressImageRatio(file,destFileSize);
            }
            return new FileInputStream(file);
        }
    }

4、上传如图

在这里插入图片描述
在这里插入图片描述

<hr style=" border:solid; width:100px; height:1px;" color=#000000 size=1">

随心所往,看见未来。Follow your heart,see night!<br/>

欢迎点赞、关注、留言,一起学习、交流!

举报

相关推荐

0 条评论