import { ImagePicker } from "@ionic-native/image-picker";
import { Camera } from '@ionic-native/camera';
import { FileTransfer, FileTransferObject } from "@ionic-native/file-transfer";
import {ImagePicker} from "@ionic-native/image-picker";
import { Camera, CameraOptions } from '@ionic-native/camera';
import {FileTransfer, FileTransferObject, FileUploadOptions} from "@ionic-native/file-transfer";
constructor(public navCtrl: NavController, public navParams: NavParams,
public toastCtrl: ToastController,
private http: HttpClient,
public modalCtrl: ModalController,
private imagePicker: ImagePicker,
private transfer: FileTransfer,
private camera: Camera,
public actionSheetCtrl: ActionSheetController,
public events:Events
)
selectPictures() {
let actionSheet = this.actionSheetCtrl.create({
title: '上传图片',
buttons: [
{
text: '拍照',
role: 'destructive',
handler: () => {
this.openCamera();
}
},
{
text: '从相册选择',
role: 'destructive',
handler: () => {
this.getPicture();
}
},
{
text: '取消',
role: 'cancel',
handler: () => {
}
}
]
});
actionSheet.present();
}
upload(file,uuid) {
let options: FileUploadOptions = {
fileKey: 'file',
fileName: 'applyrefund_' + uuid + "." + this.getFileType(file),
mimeType: this.getFileMimeType(this.getFileType(file)),
headers: {}
};
let url=encodeURI(GlobalConfig.ApiURL + this.imgUrl);
this.fileTransfer.upload(
file,
url,
options)
.then((data) => {
let strall=JSON.parse(JSON.stringify(data.response));
let str1= strall.substring(7,strall.lastIndexOf(","));
let obj=JSON.parse(str1);
this.miaosulist.push({src:'',id:obj.id,img:obj.thumbnailProductImagePath});
this.applyrefund.evalueateuuid.push(obj.id);
this.applyrefund.evalueateImages.push(JSON.stringify(data.response));
if(this.miaosulist.length>2){
this.flg = '1'
}
}, (err) => {
this.toastCtrl.create({
message: '上传失败,请重新选择',
duration: 2000,
position: 'top'
}).present();
})
}
/**
* 打开摄像头
*/
openCamera(){
const options: CameraOptions = {
quality: 60, //图片的质量
sourceType: 1, //从图库中获取图片 camera.PictureSourceType.PHOTOLIBRARY,从拍照获取图片 this.camera.PictureSourceType.CAMERA
correctOrientation: true, //是否纠正拍摄照片的方向-陀螺仪
destinationType: this.camera.DestinationType.FILE_URI, //DATA_URL 是 base64 FILE_URI 是文件路径 NATIVE_URI
encodingType: this.camera.EncodingType.JPEG,
mediaType: this.camera.MediaType.PICTURE,
saveToPhotoAlbum: true //是否保存到相册
}
this.camera.getPicture(options).then((imageData) => {
let uuid= this.uuid();
this.upload(imageData,uuid);
}, (err) => {
});
}
// 从相册选择
getPicture() {
let golbalThis = this;
let options = {
maximumImagesCount: 3-this.miaosulist.length,// 上传图片的张数限制
outputType: 0, // 图片转换的格式0:uri/1:base64
quality: 30 // 图片质量
};
this.imagePicker.getPictures(options).then((results) => {
for (let i = 0; i < results.length; i++) {
// 保存图片到html控件
let uuid= this.uuid();
golbalThis.upload(results[i],uuid);
}
}, (err) => {
console.log(err);
});
}
@Controller
@RequestMapping("/upload")
public class UploadConrtoller {
/**
* 上传图片
* @param request
* @return
* @throws Exception
*/
@RequestMapping(value = "/saveImg", method = RequestMethod.POST)
@ResponseBody
public JSONObject saveImg(HttpServletRequest request, HttpServletResponse response) throws Exception {
response.setHeader("Access-Control-Allow-Origin", "*");
JSONObject returnData = new JSONObject();
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
Iterator a =multipartRequest.getFileNames();
if(a.hasNext()){
MultipartFile filedata= multipartRequest.getFile(a.next());
if (filedata != null && !filedata.isEmpty()) {
// 获取图片的文件名
String fileName = filedata.getOriginalFilename();
// 获取文件夹(product wolland tree user)
String filepath = "";
if(fileName.split(ConstantUtils.EXTENSION_UNDERLINE).length>1){
filepath = fileName.split(ConstantUtils.EXTENSION_UNDERLINE)[0];
}
fileName.split(ConstantUtils.EXTENSION_UNDERLINE);
// 获取图片的扩展名
String extensionName = fileName.substring(fileName.lastIndexOf(".") + 1);
String allowedUploadImageExtension = ConstantUtils.ALLOWED_UPLOAD_IMAGE;
String[] imageExtensionArray = allowedUploadImageExtension.split(ConstantUtils.EXTENSION_SEPARATOR);
if (!ArrayUtils.contains(imageExtensionArray,extensionName)) {
returnData.put("success", false);
returnData.put("message","只允许上传图片文件类型: "
+ allowedUploadImageExtension + "!");
return returnData;
}else if (filedata.getSize()>ConstantUtils.EXTENSION_LENGTH){
returnData.put("success", false);
returnData.put("message","此上传文件大小超出限制!");
return returnData;
}
// 新的图片文件名 = 获取时间戳+"."图片扩展名
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
String dateString = simpleDateFormat.format(new Date());
String uuid = CommonUtil.getUUID();
String sourceProductImagePath = ConstantUtils.OBLIQUE_LINE +filepath + dateString + ConstantUtils.OBLIQUE_LINE + uuid + "." + extensionName;
String thumbnailProductImagePath = ConstantUtils.OBLIQUE_LINE + filepath + dateString + ConstantUtils.OBLIQUE_LINE + uuid + ConstantUtils.THUMBNAIL_USER_IMAGE_FILE_NAME_SUFFIX + "." + ConstantUtils.PRODUCT_USER_FILE_EXTENSION;
String serverPath = new File(System.getProperty("jboss.server.base.dir")).getParentFile().getPath();
String sourceProductImageRealPath = serverPath + ConstantUtils.UPLOAD_IMAGE_PATH+ sourceProductImagePath;
String thumbnailProductImageRealPath = serverPath +ConstantUtils.UPLOAD_IMAGE_PATH+ thumbnailProductImagePath;
File sourceProductImageFile = new File(sourceProductImageRealPath);
File thumbnailProductImageFile = new File(thumbnailProductImageRealPath);
/* 构建文件目录 */
if (!sourceProductImageFile.getParentFile().exists()) {
sourceProductImageFile.getParentFile().mkdirs();
}
if (!thumbnailProductImageFile.getParentFile().exists()) {
thumbnailProductImageFile.getParentFile().mkdirs();
}
try {
//String s=(new File("")).getAbsolutePath();
//String s =request.getSession().getServletContext().getRealPath(fileName);
filedata.transferTo(sourceProductImageFile);
BufferedImage srcBufferedImage = ImageIO.read(sourceProductImageFile);
// 图片缩略图处理
ImageUtil.zoom(srcBufferedImage, thumbnailProductImageFile, ConstantUtils.THUMBNAIL_IMAGE_HEIGHT, ConstantUtils.THUMBNAIL_IMAGE_WIDTH);
UserImage userImage = new UserImage();
userImage.setId(uuid);
userImage.setSourceProductImagePath(sourceProductImagePath);
userImage.setThumbnailProductImagePath(thumbnailProductImagePath);
//String jsonText = JSON.toJSONString(userImage);
returnData.put("success", true);
returnData.put("img", userImage);
} catch (Exception e) {
returnData.put("success", false);
returnData.put("message", "上传图片失败");
}
}
}
return returnData;
}
关于照片回显这一块非常头痛,如果直接用取得的手机中照片URL地址回西显偶尔会出现取不到照片的情况,所以暂时以服务器中上传后的照片作为回显,但是此方法回导致回显速度慢,有大佬知道原因可以私信我。