上传图片
最近在做一个上传图片的功能,因为接触yii2时间不长,所以不了解有什么好的方法实现,网上找了几种方法,虽然的确都能实现,但是都是手机端和php实现的方式。和yii2实现方式得资料貌似很少。所以记录如下
一 swift端
1.首先从相册选择图片
//图库 - 照片
func photoLib(){
//
flag = "图片"
//判断设置是否支持图片库
if UIImagePickerController.isSourceTypeAvailable(.photoLibrary){
//初始化图片控制器
let picker = UIImagePickerController()
//设置代理
picker.delegate = self
//指定图片控制器类型
picker.sourceType = UIImagePickerController.SourceType.photoLibrary
//弹出控制器,显示界面
self.present(picker, animated: true, completion: {
() -> Void in
})
}else{
print("读取相册错误")
}
}
2.系统回掉
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
if flag == "视频" {
//获取选取的视频路径
let videoURL = info[UIImagePickerController.InfoKey.mediaURL] as! URL
let pathString = videoURL.path
print("视频地址:\(pathString)")
//图片控制器退出
self.dismiss(animated: true, completion: nil)
let outpath = NSHomeDirectory() + "/Documents/\(Date().timeIntervalSince1970).mp4"
//视频转码
self.transformMoive(inputPath: pathString, outputPath: outpath)
}else{
//flag = "图片"
//获取选取后的图片
let pickedImage = info[UIImagePickerController.InfoKey.originalImage] as! UIImage
//转成jpg格式图片
guard let jpegData = pickedImage.jpegData(compressionQuality:0.5) else {
return
}
//上传
self.uploadImage(imageData: jpegData)
//图片控制器退出
self.dismiss(animated: true, completion:nil)
}
}
3.上传图片到服务器
//上传图片到服务器
func uploadImage(imageData : Data){
Alamofire.upload(
multipartFormData: { multipartFormData in
//采用post表单上传
// 参数解释:
//withName:和后台服务器的name要一致 ;fileName:可以充分利用写成用户的id,但是格式要写对; mimeType:规定的,要上传其他格式可以自行百度查一下
multipartFormData.append(imageData, withName: "imageFile", fileName: "123456.jpg", mimeType: "image/jpeg")
//如果需要上传多个文件,就多添加几个
//multipartFormData.append(imageData, withName: "file", fileName: "123456.jpg", mimeType: "image/jpeg")
//......
},to: uploadURL,method: .post,encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
//连接服务器成功后,对json的处理
upload.responseJSON { response in
//解包
guard let result = response.result.value else { return }
print("json:\(result)")
}
//获取上传进度
upload.uploadProgress(queue: DispatchQueue.global(qos: .utility)) { progress in
print("图片上传进度: \(progress.fractionCompleted)")
}
case .failure(let encodingError):
//打印连接失败原因
print(encodingError)
}
})
}
二 php端
1、新建一个Controller
class TestController extends Controller
{
public function actionUpload()
{
$model = new UploadForm();
if (Yii::$app->request->isPost) {
$model->imageFile = UploadedFile::getInstance( "imageFile");
if ($model->upload()) {
// 文件上传成功
return ;
}
}
return $this->render('index', ['model' => $model]);
}
}
其中UploadedFile是改写了的,源码里面的适合接受网页提交的,修改如下,就可以正常接受了
2.
class UploadForm extends Model
{
/**
* @var UploadedFile
*/
public $imageFile;
// public function rules()
// {
// return [
// [['imageFile'], 'file', 'skipOnEmpty' => false, 'extensions' => 'png, jpg, jpeg'],
// ];
// }
public function upload()
{
if ($this->validate()) {
$this->imageFile->saveAs('../web/upload/' . $this->imageFile->baseName . '.' . $this->imageFile->extension);
return true;
} else {
return false;
}
}
}
这样就可以顺利实现PHP端和ios端交互了。
源码如下 php 源码 https://github.com/hwhjxjs/tplapiNew.git
ios源码 https://github.com/hwhjxjs/uploadPicDemo.git
网友评论