angularjs上传图片并转换成base64保存到数据库(代码片段)

rage_angel rage_angel     2023-03-24     116

关键词:

1、前台:

jsp

<div style="width: 160px;height: 130px;border-radius: 16px;position: relative;">
    <a href="javascript:;"
       style="position: absolute;width: 100%;height: 100%;">
        <div style="width: 100%;height: 100%;">
            <img ng-if="loginedAccount.photo" id="photo" width="100%" height="100%" ng-src="data.photodata">
            <img ng-if="!loginedAccount.photo" id="photo" width="100%" height="100%" src="images/g1.jpg">
        </div>
        <input id="file" file-model="data.photo_file" type="file" style="width: 100%;height: 100%;position: absolute;top: 0;left: 0;z-index: 4;opacity: 0;">
    </a>
</div>
js
<pre name="code" class="javascript">var limitSize = 1 * 1024 * 1024;
  $scope.$watch("data.photo_file", function (newValue, oldValue) 
    if ($scope.data && $scope.data.photo_file) 
      if (!oldValue || newValue.size != oldValue.size) 
        if (newValue.size <= limitSize) 
          var file = document.getElementById("file").files[0];
          $("#photo").attr("src", window.URL.createObjectURL(file));
         else 
          alert("图片大小不得超过1M!");
        
      
    
  );


记得引js包。
 
<script src="bower_components/angular-file-upload/dist/angular-file-upload.min.js"></script>

2、springmvc-servlet.xml配置文件配置:
	<!-- 处理文件上传 -->
	<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		<!--1024*2000即2M-->
		<property name="maxUploadSize" value="2048000"/>
		<!--resolveLazily属性启用是为了推迟文件解析,以便在UploadAction 中捕获文件大小异常-->
		<property name="resolveLazily" value="true"/>

		<property name="uploadTempDir" value="/WEB-INF/upload"/>
		<!-- 上传后的目录名 (WebUtils#TEMP_DIR_CONTEXT_ATTRIBUTE) -->
		<property name="maxInMemorySize" value="2048000"/>
		<property name="defaultEncoding" value="UTF-8"/>
	</bean>
3、在build.gradle配置文件中添加上传所需要的包。
compile group: 'commons-fileupload', name: 'commons-fileupload', version:'1.3.1'
    compile group: 'commons-io', name: 'commons-io', version:'2.4'
4、后台
public ViewData getXXX(@RequestParam MultipartFile[] photo_file, String xx, String xx, String xx, String xx, String xx,
                               HttpServletRequest request) 
        ViewData vd = new ViewData();
        String base64photo = "";
        if (photo_file != null && photo_file.length > 0) 
//            System.out.println("文件大小:" + photo_file[0].getSize());
            MultipartFile file = photo_file[0];
            if (file.getSize() < 1 * 1024 * 1024) 
                //获取图片的字节流
                byte[] bytePhoto = FileUtils.file2Byte(photo_file[0]);
                //压缩图片
                base64photo = FileUtils.resize(bytePhoto, 300, 0.7f);
//                System.out.println("字符长度:" + base64photo.length());
             else 
                return vd.error("照片大小不能超过1M!");
            
        
        ....
    
FileUtils
/** 文件转字节
     * @param file
     * @return
     */
    public static byte[] file2Byte(MultipartFile file) 
        byte[] buffer = null;
        ByteArrayOutputStream bos = null;
        try 
            InputStream inputStream = file.getInputStream();
            bos = new ByteArrayOutputStream(4096);
            byte[] b = new byte[4096];
            int n;
            while ((n = inputStream.read(b)) != -1) 
                bos.write(b, 0, n);
            
            file.getInputStream().close();
            bos.close();
            buffer = bos.toByteArray();
//            BASE64Encoder encoder = new BASE64Encoder();
//            base64photo = encoder.encode(buffer);
//            System.out.println("照片流64:" + encoder.encode(buffer));
         catch (Exception e) 
            e.printStackTrace();
         finally 
            try 
                if (bos != null)  bos.close(); 
             catch (IOException e) 
            
        
        return buffer;
    

    /**
     * 压缩图片
     * @param b 图片的字节流
     * @param newWidth 压缩的宽度
     * @param quality 压缩质量 0-1之间float类型
     * @return
     * @throws IOException
     */
    public static String resize(byte[] b,int newWidth, float quality)
        if (quality > 1) 
            throw new IllegalArgumentException("Quality has to be between 0 and 1");
        
        String baseStr = "";
        ByteArrayOutputStream byteArrayOutputStream = null;
        try
            ImageIcon ii = new ImageIcon(b);
            Image i = ii.getImage();
            Image resizedImage = null;

            int iWidth = i.getWidth(null);
            int iHeight = i.getHeight(null);

            if (iWidth > iHeight) 
                resizedImage = i.getScaledInstance(newWidth,(newWidth * iHeight)
                        / iWidth,  Image.SCALE_SMOOTH);
             else 
                resizedImage = i.getScaledInstance((newWidth * iWidth) / iHeight,
                        newWidth, Image.SCALE_SMOOTH);
            

            // This code ensures that all the pixels in the image are loaded.
            Image temp = new ImageIcon(resizedImage).getImage();

            // Create the buffered image.
            BufferedImage bufferedImage = new BufferedImage(temp.getWidth(null),
                    temp.getHeight(null), BufferedImage.TYPE_INT_RGB);

            // Copy image to buffered image.
            Graphics g = bufferedImage.createGraphics();

            // Clear background and paint the image.
            g.setColor(Color.white);
            g.fillRect(0, 0, temp.getWidth(null), temp.getHeight(null));
            g.drawImage(temp, 0, 0, null);
            g.dispose();

            // Soften.
            float softenFactor = 0.05f;
            float[] softenArray = 0, softenFactor, 0, softenFactor,
                    1 - (softenFactor * 4), softenFactor, 0, softenFactor, 0;
            Kernel kernel = new Kernel(3, 3, softenArray);
            ConvolveOp cOp = new ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP, null);
            bufferedImage = cOp.filter(bufferedImage, null);

            byteArrayOutputStream = new ByteArrayOutputStream(4096);
            // Encodes image as a JPEG data stream
            JPEGImageEncoder imgEncoder = JPEGCodec.createJPEGEncoder(byteArrayOutputStream);
            JPEGEncodeParam param = imgEncoder.getDefaultJPEGEncodeParam(bufferedImage);
            param.setQuality(quality, true);
            imgEncoder.setJPEGEncodeParam(param);
            imgEncoder.encode(bufferedImage);

            //转换成64字节码
            BASE64Encoder encoder = new BASE64Encoder();
            baseStr = encoder.encode(byteArrayOutputStream.toByteArray());
        catch (IOException e)
            e.printStackTrace();
        
//        File resizedFile = new File("/Users/jennifer/Documents/11111.jpg");
//        FileOutputStream out = new FileOutputStream(resizedFile);
//        out.write(byteArrayOutputStream.toByteArray());
//        out.close();
        return baseStr;
     // Example usage





java上传不同类型图片,保存数据库(base64位图转网络图片)

直接上代码好不好方法名:GenerateImage传参:base64Img:上传的base64码realPath:生成的图片路径 imgTypes:图片类型 StringimgBase64=request.getParameter("userImgbase64");//获取当前服务器路径 StringrealPath=request.getServletContext().ge 查看详情

拍照并转成Base64

】拍照并转成Base64【英文标题】:TakepictureandconverttoBase64【发布时间】:2016-07-1109:54:33【问题描述】:我使用下面的代码用相机拍照。我不想保存,而是将其编码为Base64,然后将其作为输入传递给另一个API。我看不到方法,如何... 查看详情

上传图片转换格式为base64并预览

<inputtype=‘file‘id=‘fileEl‘/>functionbase64()letfileObj=document.getElementById(‘fileEl‘).files[0]//获取文件对象letreader=newFileReader()//新建一个FileReader对象reader.readAsDataURL(fileObj)//将读取的文件转换成base64格式reader.onload=function(e)document.getE... 查看详情

tp5base64图片上传

/***保存图片*/publicfunctionuploads($value=‘‘)//$file=base64_decode(request()->file(‘image‘));//图片$param=input(‘param.‘);$up_dir=ROOT_PATH.‘public‘.DS.‘uploads/‘;//存放在当前目录的upload文件夹下$base64_img=trim($ 查看详情

前端批量上传图片后端怎么接收?

...,这里也不好判断是否是接收问题追问前端是用ajax方式上传的,就是不知道后端如何接收多张图片。 参考技术B循环啊异步啊,直接转换成base64传到后台,后台循环解码,保存在文件夹里面不就可以了。 查看详情

ipcloud上传裁切图片,保存为base64再压缩传给后台

<!doctypehtml><html><head><metacharset="utf-8"><metaname="viewport"content="maximum-scale=1.0,minimum-scale=1.0,user-scalable=0,width=device-width,initial-scale=1.0"/>< 查看详情

vue上传图片时base64怎么传到java后台

vue上传图片时候为了预览保存的是base64的一串字符串,我现在把这个传到后台怎么把它转换成文件的形式1、org.apache.commons.codec.binary.Base64.decodeBase64(这里传入src属性里的base64的一串字符串);2、返回值是一个Byte[];3、字节流传送到... 查看详情

base64上传到oss

1.将base64转换为blob[-- oss支持直接从客户端提交base64编码保存图片吗 --] //**dataURLtoblob**functiondataURLtoBlob(dataurl) debugger vararr=dataurl.split(‘,‘),mime=arr[0].match(/:(.*?);/)[1], bstr=atob(arr[1]),n 查看详情

php将base64图片转换为本地图片并保存(代码片段)

PHP将Base64图片转换为本地图片并保存/***[将Base64图片转换为本地图片并保存]*@param[Base64]$base64_image_content[要保存的Base64]*@param[目录]$path[要保存的路径]*/functionbase64_image_content($base64_image_content,$path)//匹配出图片的格式if(preg_mat 查看详情

base64转图片上传

不成功,但是有一定的借鉴性/** *@parambase64Codes *      图片的base64编码 */functionsumitImageFile(base64Codes){//debuggerconsole.log(convertBase64UrlToBlob(base64Codes));&nb 查看详情

data:。image/png,base64,………源图片需要上传到服务器空间吗,如不上传,那源图

data:。image/png,base64,………源图片需要上传到服务器空间吗,如不上传,那源图片该保存到哪里呢,参考技术A肯定需要传到服务器空间里面的,不然怎么调用图片。图片显示指定的路径就是存放的路径。追问可是,我把图片上... 查看详情

php图片上传为啥要base64上传

参考技术A可以让别人看不到你的路径,还要base64可以存入数据库, 参考技术B两点:base64的编码原理,大小比原文件大小大1/3base64无法缓存,要缓存只能缓存包含base64的文件 查看详情

记录一个简单webapi上传图片

图片转base64字符串,到接口后,再转回保存.代码里面是转成byte[]之后转的,也可以用base64字符串直接转图片.只想记录一下简单的流程。1,服务端保存图片业务代码: publicclassUpLoadFile         ... 查看详情

上传base64图片到服务器

】上传base64图片到服务器【英文标题】:Uploadbase64imagetoserver【发布时间】:2018-04-1714:04:31【问题描述】:我正在使用Alamofire和swiftyJson我想将图片作为base64上传到服务器,我使用此代码上传我的图片classfuncuploadMultipleAdvertisementImag... 查看详情

php图像文件上传并转换为base64而不保存图像

】php图像文件上传并转换为base64而不保存图像【英文标题】:phpimagefileuploadandconverttobase64withoutsavingimage【发布时间】:2013-10-2013:22:21【问题描述】:我知道如何使用以下代码上传图像文件并保存到其他位置。但是,我需要这样做... 查看详情

base64格式的图片如何上传到oss

---恢复内容开始---对于base64图片的上传这个东西,一直是一个问题尤其是上传到oss。我们这次开发由于需要修剪图片,使用了h5的很多新特性。h5修剪图片,使用了我们的canvas。这个步骤是这样的。img->canvas->base64(bytoDataURL)。... 查看详情

对图片中的表格进行识别,并转换成excel文件(python小软件)(批量)(代码片段)

文章目录一、python调用腾讯接口二、python+百度API识别图片中表格并保存到excel三、小马识图识别工具一、python调用腾讯接口识别效果就比较拉胯,这个SecretId和SecretKey需要你自己去申请,不难,去腾讯云捣鼓吧。htt... 查看详情

springboot上传/返回图片与base64转换(代码片段)

配置默认情况下,在springboot嵌入的tomcat限制了上传文件的大小,在springboot的我官方文档中说明,每个文件的最大配置为1Mb,单次请求的总文件数不能大于10Mb。这意味着如果你上传的图片大于1Mb,会被拦截下... 查看详情