服务器端上传图片和查询图片的代码 @Controller @RequestMapping ({ "/attachment" }) @CrossOrigin // 允许跨域访问 @PropertySource ( "classpath:file.properties" ) public class AttchmentController extends BaseController { //
服务器端上传图片和查询图片的代码
@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:) {
}//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="">图片效果
自此,大功告成!(最喜欢的一句话)