Element组件--Upload文件/图片上传

利用Element组件–上传图片至文件服务器----前后端代码

前端代码:

 <div style="width: 50%;height: 100%;float: right;margin-top: 50px;text-align: center" >
                <div style="text-align: center;margin-bottom: 20px">点击区域或拖入图片进行图片编辑</div>
                <el-upload
                  ref="upload"
                  :action="actionPath"
                  drag
                  :multiple="isMultiple"
                  :on-success="onUploadSuccess"
                  :on-error="onUploadError"
                  :with-credentials="isCredentials"
                  :limit="uploadLimit">
                  <img style="width: 300px;height: 300px"  slot="trigger" :src="editData.awardImage" />
                </el-upload>
              </div>
       <el-dialog
        title="提示"
        :visible.sync="isShowDialog"
        width="30%"
        @close="closeDialog"
        :modal="isModal"
      >
        <span>{
   
   {dialogMessage}}</span>
      </el-dialog>

变量:

 export default {
        name: "xxxManager",
        data(){
          return{
            actionPath:"http://xxx/uploadImg.do",
            isCredentials:true,
            isMultiple:false,
            uploadLimit:1,
            editData:{
              id:"",
              awardImage:"",
            }
            },
            methods:{
             //文件上传成功
          onUploadSuccess(res, file){
            console.log(res);
                this.editData.awardImage = res;
                console.log(this.editData.awardImage);
                this.isShowDialog = true;
                this.dialogMessage = "文件上传成功!";
                this.$refs.upload.clearFiles();
                return;
          },
           //关闭弹窗
          closeDialog(){
            this.isShowDialog = true;
          },
          //文件上传失败
          onUploadError(err, file){console.log(err);
              this.isShowDialog = true;
              this.dialogMessage = "上传文件出错,请重试!";
              this.$refs.upload.clearFiles();
              return;
          },
           closeUploadDialog(){
            this.centerDialogVisible = false;
            this.initEditData();//初始化弹窗内容
          },
            }

后端代码:

controller层

@RequestMapping(value = "uploadImg",method = RequestMethod.POST)
    public String uploadImg(@RequestParam("file") MultipartFile file){
    
    
        if(file == null){
    
    
            throw new AppException("请选择文件!");
        }
        return xxxService.uploadImg(file);

    }

service层

 public String uploadImg(MultipartFile file){
    
    

        String imgPath = "";
        try {
    
    
                byte[] content = file.getBytes();
                InputStream inputStream = new ByteArrayInputStream(content);
                Path path = new Path("/xxx/xxx/"+ System.currentTimeMillis()+"/");
                BufferedImage bufferedImage = ImageIO.read(inputStream);
                BufferedImage image = imageUntil.getThumbnail(bufferedImage,375,375);
                CosResult result =  tencentCosService.uploadFileToCos(path,System.currentTimeMillis() + ".png",fileUtils.convertBuffered(image));
                imgPath = result.getCdnUrl();
        }catch (IOException e){
    
    
            log.error("文件上传IO出错!");
            throw new AppException("文件上传IO出错!");
            //return WhhRestResult.server_error().message("文件上传IO出错!");
        }catch (Exception e){
    
    
            log.error("文件上传出错!");
            throw new AppException("文件上传出错!");
            //return WhhRestResult.server_error().message("文件上传出错!");
        }

        //return WhhRestResult.ok().data(imgPath);
        return imgPath;

    }```
**-
-
-
-**
//目标图片的高度与宽度--- imageUntil.getThumbnail(bufferedImage,375,375);

imageUntil类如下:

```java
public  BufferedImage getThumbnail(final BufferedImage  sourceImage,int width,int height) throws Exception {
    
    
        int sourceHeight=sourceImage.getHeight();
        int sourceWidth=sourceImage.getWidth();
        BufferedImage thumbnail;
        if((float)sourceWidth/sourceHeight==(float)(width/height)) {
    
    
            thumbnail = Thumbnails.of(sourceImage).size(width, height).keepAspectRatio(false).asBufferedImage();
        }
        //宽度略宽,裁切Y轴方向
        else if((float)sourceWidth/sourceHeight>(float)(width/height))
        {
    
    
            if(sourceHeight < height){
    
    
                thumbnail = Thumbnails.of(sourceImage).sourceRegion(Positions.TOP_CENTER,sourceHeight*width/height,sourceHeight)
                        .size(width, sourceHeight).keepAspectRatio(false).asBufferedImage();
            }else {
    
    
                thumbnail = Thumbnails.of(sourceImage).sourceRegion(Positions.CENTER,sourceHeight*width/height,sourceHeight)
                        .size(width, height).keepAspectRatio(false).asBufferedImage();
            }
        }
        //高度略高,裁切X轴方向
        else
        {
    
    
            if(sourceHeight < height){
    
    
                thumbnail = Thumbnails.of(sourceImage).sourceRegion(Positions.CENTER,sourceWidth,sourceWidth*height/width)
                        .size(width, sourceHeight).keepAspectRatio(false).asBufferedImage();
            }else {
    
    
                thumbnail = Thumbnails.of(sourceImage).sourceRegion(Positions.CENTER,sourceWidth,sourceWidth*height/width)
                        .size(width, height).keepAspectRatio(false).asBufferedImage();
            }
        }
        return thumbnail;
    }

TencentCosService类如下:
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.COSClient;

 private String tencentBucketName;
public CosResult uploadFileToCos(Path path, String fileName, byte[] content) {
    
    
        try {
    
    
            InputStream input = new ByteArrayInputStream(content);
            String key = path.getPath() + fileName;
            //File localFile = new File("src/test/resources/len10M.txt");
            //InputStream input = new ByteArrayInputStream(new byte[10]);
            ObjectMetadata objectMetadata = new ObjectMetadata();
            // 从输入流上传必须制定content length, 否则http客户端可能会缓存所有数据,存在内存OOM的情况
            objectMetadata.setContentLength(content.length);
            // 设置contenttype默认下载时根据cos路径key的后缀返回响应的contenttype, 上传时设置contenttype会覆盖默认值
            //objectMetadata.setContentType("image/jpeg");
            PutObjectRequest putObjectRequest =
                    new PutObjectRequest(tencentBucketName, key, input, objectMetadata);
            // 设置存储类型, 默认是标准(Standard), 低频(standard_ia)
            putObjectRequest.setStorageClass(StorageClass.Standard);
            CosResult cosResult = new CosResult();
            PutObjectResult putObjectResult = tencentCOSClient.putObject(putObjectRequest);
            // putobjectResult会返回文件的etag
            String etag = putObjectResult.getETag();
            cosResult.setFileKey(key);
            //https://xxxxhai.myqcloud.com/v2-db2f5c4e0a51e644a58a93273ff6d5bd_b.jpg
            cosResult.setCosUrl(
                    "https://" + tencentBucketName + ".cos." +
                           tencentCOSClient.getClientConfig().getRegion().getRegionName() +
                            ".myqcloud.com" + key);
            cosResult.setCdnUrl("https://" + tencentCName + key);
            return cosResult;
        } catch (Exception e) {
    
    
            e.printStackTrace();
            return null;
        } finally {
    
    
            // 关闭客户端
            tencentCOSClient.shutdown();
        }
    }

猜你喜欢

转载自blog.csdn.net/qq_40579139/article/details/109401782