ionic3 + springmvc/springboot + angular圖片上傳以及渲染
阿新 • • 發佈:2018-12-20
伺服器端上傳圖片和查詢圖片的程式碼
@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="">圖片
效果
自此,大功告成!(最喜歡的一句話)