ionic3 + springmvc/springboot + angular图片上传以及渲染

简介: ionic3 + springmvc/springboot + angular图片上传以及渲染

服务器端上传图片和查询图片的代码


@Controller
@RequestMapping({"/attachment"})
@CrossOrigin // 允许跨域访问
@PropertySource("classpath:file.properties")
public class AttchmentController extends BaseController {
//    @Value("${file.server}")
    private String serverUri = "172.19.1.225:8001";
    /**
     * 通过 RestTemplate 调用远程文件上传服务
     *
     * @param file
     * @return
     */
//    @ApiOperation(httpMethod = "POST", value = "文件上传", response = JsonResult.class)
    @RequestMapping(value = "/uploadFiles", method = RequestMethod.POST)
    @ResponseBody
    public void uploadFilesTemp(MultipartFile file,HttpServletRequest request, final HttpServletResponse response) {
        final Json j = new Json();
        String fileName = StringUtils.cleanPath(file.getOriginalFilename()) + ".jpg";
        if (file.isEmpty()) {
            j.setSuccess(false);
            j.setMsg("无法保存空文件!");
        }
        if (fileName.contains("..")) {
            // 安全检查
            j.setSuccess(false);
            j.setMsg("无法存储当前目录外的相对路径的文件" + fileName);
        }
        //生成临时文件,将 MultipartFile 转成 File
        File tempFile = null;
        // 用uuid作为文件名,防止生成的临时文件重复
        String prefix = UUID.randomUUID().toString().replaceAll("-", "");
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        try {
            tempFile = File.createTempFile(prefix, suffix);
            file.transferTo(tempFile);
            //构建 HttpEntity
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.MULTIPART_FORM_DATA);
            MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
            body.add("file", new FileSystemResource(tempFile));
            HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);
            //文件上传远程接口
            String serverUrl = "http://" + serverUri + "/handleFileUpload";
            RestTemplate restTemplate = new RestTemplate();
            restTemplate.postForEntity(serverUrl, requestEntity, String.class);
            Map<String, Object> resultMap = new HashMap<>(3);
            String tempFileName = tempFile.getName();
            resultMap.put("originalFileName", fileName);
            //加载图片的地址
            String loadFileUrl =  "/attachment/files/"+tempFileName;
            resultMap.put("fileName", loadFileUrl);
            resultMap.put("size", file.getSize());
            //resultMap:{originalFileName=image%3A560647.jpg, size=2612721, fileName=/attachment/files/1ee588f26f2d4bd6af7bc4a63978be65924011332072368680.jpg}
            j.setSuccess(true);
            j.setMsg("上传成功!");
            j.setObj(resultMap);
        } catch (IOException e) {
            e.printStackTrace();
            j.setSuccess(false);
            j.setMsg(e.getMessage());
        } finally {
            if (tempFile != null) {
                tempFile.delete();
            }
        }
        this.writeJson(j, request, response);
    }
    /**
     * 查询文件
     *
     * @param filename
     * @return
     */
    @RequestMapping("/files/{filename:.+}")
    public ResponseEntity<Resource> serveFile(@PathVariable String filename) {
        RestTemplate restTemplate = new RestTemplate();
        String fileUrl = "http://" + serverUri + "/files/" + filename;
        ResponseEntity<Resource> entity = restTemplate.getForEntity(fileUrl, Resource.class);
        return entity;
    }
}



ionic3 端上传和请求图片的代码


先引入


1.在需要使用外部url链接的ts文件中,引入DomSanitizer类

import { DomSanitizer } from '@angular/platform-browser';
constructor(public navCtrl: NavController, public storage: StorageProvider, public navParams: NavParams, public http: HttpProvider,
              public apiService: ApiServiceProvider, private sanitizer: DomSanitizer) {
  }


//2.在需要使用转换后的url地方加上
  getSafeUrl(url){
    return this.sanitizer.bypassSecurityTrustResourceUrl(url);
  }


//声明变量
 url;


上传代码

export class FileDataPage {
fileDataNum:number = 0;
path:any = [];
data: string = "";
fileTransfer: FileTransferObject = this.transfer.create();
constructor(public navCtrl: NavController, public navParams: NavParams,private viewCtrl:ViewController,
            private transfer: FileTransfer,private camera: Camera,private apiService:ApiServiceProvider) {
}
uploadFiles: this.http.domain + '/attachment/uploadFiles.do', //上传附件
doUpload(filePath) {
  const fileTransfer: FileTransferObject = this.transfer.create();
  let options: FileUploadOptions = {
    fileKey: 'file',
    fileName:this.path,
    params: {
      maxSize: 5000000,
      modularName: 'CNL',
      allowType: 'jpg;png',
    },
    headers: {}
  };
  let api = this.apiService.url.uploadFiles; //上传接口地址
  fileTransfer.upload(filePath,api,options).then(
    (data) => {
      alert(data);
    },(err) => {
      console.error(err);
      alert(JSON.stringify(err));
    }
  )
}


ionic3 显示图片


ionViewDidLoad() {
    //修复轮播手动滑动后不能自动轮播问题
    this.slides.autoplayDisableOnInteraction = false;
    this.loadMenu();
    this.loadImage();
  }
  loadImage(){
    let path = '/attachment/files/9d82255765144419997bd0f0296a2499916200506861957264.jpg';
    this.http.get(this.http.domain + path, {},{
      responseType: "blob"
    }).subscribe(res => {
      console.log(res);
      var blob = new Blob([res], {type: "image/jpeg"});
      //this.url = window.URL.createObjectURL(blob);
      this.url = this.getSafeUrl(URL.createObjectURL(blob));
      console.log(this.url);
    });
  }


页面图片


<img [src]="url" alt="">图片


效果

1dc618a0ed9580ce8bfa6facb208c08f.png

相关文章
|
7天前
|
前端开发 Java 开发者
Spring Boot中使用Thymeleaf进行页面渲染
Spring Boot中使用Thymeleaf进行页面渲染
|
7天前
|
前端开发 Java Spring
Spring Boot中使用Thymeleaf进行页面渲染
Spring Boot中使用Thymeleaf进行页面渲染
|
10天前
4.springboot视图渲染技术
4.springboot视图渲染技术
6 0
|
2月前
|
搜索推荐 SEO 缓存
为什么 Angular 服务器端渲染只面向匿名用户,没有用户上下文
为什么 Angular 服务器端渲染只面向匿名用户,没有用户上下文
|
9月前
|
数据采集 搜索推荐 索引
Angular 服务器端渲染应用返回 HTTP 404 和 200 状态码对 SEO 的影响
Angular 服务器端渲染应用返回 HTTP 404 和 200 状态码对 SEO 的影响
|
2月前
|
网络协议 JavaScript
Angular 服务器端渲染应用里重用 TCP 连接的示例代码
Angular 服务器端渲染应用里重用 TCP 连接的示例代码
|
2月前
|
前端开发 JavaScript
Angular 组件模版代码里使用 ngIf 进行条件渲染的例子
Angular 组件模版代码里使用 ngIf 进行条件渲染的例子
|
8月前
|
数据采集 JavaScript 前端开发
Angular 服务器端渲染应用 re-hydration 过程详解
Angular 服务器端渲染应用 re-hydration 过程详解
|
8月前
|
JavaScript UED SEO
Angular 应用启用服务器端渲染后 Ngrx store 和 re-hydration 的交互关系
Angular 应用启用服务器端渲染后 Ngrx store 和 re-hydration 的交互关系
|
8月前
|
搜索推荐 API SEO
Angular 服务器端渲染的静态 HTML 变为客户端的动态应用的过程
Angular 服务器端渲染的静态 HTML 变为客户端的动态应用的过程

热门文章

最新文章