vue图片上传及java存储图片(亲测可用)

1.前言

    在使用elementui的upload组件时,我一直无法做到上传的图片和其他数据一起提交。单纯的上传文件,java的存储图片的方式也有局限性。

    我知道的后端保存图片有两种方式:一种是直接存储到数据库中(base65和blob都能做到),一种是存储在服务器上的一个文件夹,数据库保存图片地址.  

    开始我选择了base64 但是mysql貌似不允许这么长的存储长度(没有百度直接否掉了),后面就使用存储在服务器上。

2.代码

   流程是,前端选择好图片并且填充好想要填写的数据,点提交就提交到后台进行上传和其他操作。图片名称我在前端进行修改,因为我貌似没有在 MultipartRequest 类中发现修改    图片名称的方法  api地址: http://www.servlets.com/cos/javadoc/com/oreilly/servlet/MultipartRequest.html  

   项目依赖cos.jar  百度云下载地址: 链接:https://pan.baidu.com/s/1NLxxo9JTBp93A1mZ7hIWaA 密码:gf5y

   前端代码:

<template>
<div>
<el-upload class="upload-demo" action="auto" :http-request="uploadSectionFile" list-type="picture">
  <el-button size="small" type="primary">点击上传</el-button>
  <div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过2MB</div>
</el-upload>
<el-button size="small" type="primary" @click="upload">提交</el-button>
</div>
</template>
<script>
export default {
  data() {
    return {
      uploadFile: ""
    };
  },
  methods: {
    uploadSectionFile(param) {
      let fileObj = param.file;
 
      const isLt2M = fileObj.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
        return;
      }
      if (fileObj.type === "image/jpeg") {
        this.uploadFile = new File([fileObj], new Date().getTime() + ".jpg", {
          type: "image/jpeg"
        });
      } else if (fileObj.type === "image/png") {
        this.uploadFile = new File([fileObj], new Date().getTime() + ".png", {
          type: "image/png"
        });
      } else {
        this.$message.error("只能上传jpg/png文件");
        return;
      }
    },
    upload() {
      var param = new FormData(); // FormData 对象
      param.append("file", this.uploadFile); // 文件对象
      param.append("name", "ziguiyu"); // 其他参数
      this.$axios({
        method: "post",
        url: "/GradeSystem/upload.do",
        data: param
      })
        .then(response => {
         this.$message({
          message: '上传成功',
          type: 'success'
        });
        })
        .catch(error => {
          this.$message.error("上传失败,请稍后重试");
        });
    }
  }
};
</script>

后端代码

package org.huangxb.course.service;
 
 
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Enumeration;
 
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import org.huangxb.course.util.makeDirectory;
 
import com.oreilly.servlet.MultipartRequest;
import com.oreilly.servlet.multipart.DefaultFileRenamePolicy;
 
 
public class UploadImg extends HttpServlet {
 
        protected void doPost(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
 
            // 设置大小限制(单位:字节)
            final int permitedSize = 2097152;
 
            try {              
                String type = "";
                String name = "";
                String originalFilename = "";
                String filename = "";
                 
                //上传目录
                Calendar  cal  =  Calendar.getInstance();
                String uploadDate = new SimpleDateFormat( "yyyyMMdd").format(cal.getTime());//以日期为文件夹名称
                String strDirectory = "images/"+uploadDate;
                String uploadPath = request.getSession().getServletContext().getRealPath("/") + strDirectory;
                makeDirectory.mkDirectory(uploadPath);
                // 获取句柄
                MultipartRequest multipartRequest = new MultipartRequest(request, uploadPath,
                                 permitedSize, "ISO-8859-1", new DefaultFileRenamePolicy());
                     
                // 取得文件
                Enumeration files = multipartRequest.getFileNames();      
                     
                // 取得文件详细信息
                while (files.hasMoreElements()) {
                       name = (String)files.nextElement();
                       type = multipartRequest.getContentType(name);
                       filename = multipartRequest.getFilesystemName(name);
                       originalFilename = multipartRequest.getOriginalFileName(name);         
                       File currentFile = multipartRequest.getFile(name);
                }
                 
                // 取得其它非文件字段
                Enumeration params = multipartRequest.getParameterNames();
                 
                while (params.hasMoreElements()) {
                    String param = (String)params.nextElement();
                    String value = multipartRequest.getParameter(param);
                }                     
            } catch (Exception exception) {
                response.sendError(response.SC_METHOD_NOT_ALLOWED);
            } finally {
            }
             
        }
        
}
  

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package org.huangxb.course.util;
 
import java.io.File;
 
public class makeDirectory {//创建目录的类
    public static boolean mkDirectory(String path) {
        File file = null;
        try {
            file = new File(path);
            if (!file.exists()) {
                return file.mkdirs();
            }
            else{
                return false;
            }
        } catch (Exception e) {
        } finally {
            file = null;
        }
        return false;
    }
 
}

在测试时,发现upload的进度条没有了,由于不是很需要就没有去研究。小白进阶,有童鞋发现问题请指正。

你可能感兴趣的