回答編集履歴

2

修正

2016/08/15 06:43

投稿

_Kentarou
_Kentarou

スコア8490

test CHANGED
@@ -100,7 +100,7 @@
100
100
 
101
101
 
102
102
 
103
- 質問サイトのコードで実行
103
+ 質問されているコードで実行
104
104
 
105
105
  ---
106
106
 

1

修正

2016/08/15 06:43

投稿

_Kentarou
_Kentarou

スコア8490

test CHANGED
@@ -97,3 +97,313 @@
97
97
  ?>
98
98
 
99
99
  ```
100
+
101
+
102
+
103
+ 質問サイトのコードで実行
104
+
105
+ ---
106
+
107
+
108
+
109
+ 以下のコードで問題なくMAMPのフォルダに指定したフォルダが作られて画像がアップロードされました。
110
+
111
+ やはりMAMPのサーバーに問題なく繋がることを確認してから該当サイトのコードを試すほうが確実なような気がします。
112
+
113
+
114
+
115
+ `ViewController.swift`
116
+
117
+
118
+
119
+ ```swift
120
+
121
+ import UIKit
122
+
123
+ import Foundation
124
+
125
+
126
+
127
+ extension NSMutableData {
128
+
129
+ func appendString(string: String) {
130
+
131
+ let data = string.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)
132
+
133
+ appendData(data!)
134
+
135
+ }
136
+
137
+ }
138
+
139
+
140
+
141
+ class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate{
142
+
143
+
144
+
145
+ // 画面にUIImageViewを配置
146
+
147
+ @IBOutlet weak var imageForUpload: UIImageView!
148
+
149
+
150
+
151
+ // Photo Libraryを開く為のボタンアクションを追加
152
+
153
+ @IBAction func openLibrary(sender: UIButton) {
154
+
155
+ pickImageFromLibrary()
156
+
157
+ }
158
+
159
+
160
+
161
+
162
+
163
+
164
+
165
+ // ---------- 以下はアクセスするサイトURL以外は変更なし ------------
166
+
167
+
168
+
169
+
170
+
171
+
172
+
173
+
174
+
175
+ //UIImagePickerControllerDelegate, UINavigationControllerDelegateを忘れずに
176
+
177
+ //画像のアップロード処理
178
+
179
+ func myImageUploadRequest(){
180
+
181
+ //myUrlには自分で用意したphpファイルのアドレスを入れる
182
+
183
+ let myUrl = NSURL(string: "http://localhost:80/upload.php")!
184
+
185
+ let request = NSMutableURLRequest(URL:myUrl)
186
+
187
+ request.HTTPMethod = "POST"
188
+
189
+ //下記のパラメータはあくまでもPOSTの例
190
+
191
+ let param = [
192
+
193
+ "userId" : "12345"
194
+
195
+ ]
196
+
197
+ let boundary = generateBoundaryString()
198
+
199
+ request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
200
+
201
+ let imageData = UIImageJPEGRepresentation(self.imageForUpload.image!, 1)
202
+
203
+ if(imageData==nil) { return; }
204
+
205
+ request.HTTPBody = createBodyWithParameters(param, filePathKey: "file", imageDataKey: imageData!, boundary: boundary)
206
+
207
+ let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
208
+
209
+ data, response, error in
210
+
211
+ if error != nil {
212
+
213
+ print("error=\(error)")
214
+
215
+ return
216
+
217
+ }
218
+
219
+ // レスポンスを出力
220
+
221
+ print("******* response = \(response)")
222
+
223
+ let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
224
+
225
+ print("****** response data = \(responseString!)")
226
+
227
+ dispatch_async(dispatch_get_main_queue(),{
228
+
229
+ //アップロード完了
230
+
231
+ });
232
+
233
+ }
234
+
235
+ task.resume()
236
+
237
+ }
238
+
239
+ func createBodyWithParameters(parameters: [String: String]?, filePathKey: String?, imageDataKey: NSData, boundary: String) -> NSData {
240
+
241
+ let body = NSMutableData()
242
+
243
+ if parameters != nil {
244
+
245
+ for (key, value) in parameters! {
246
+
247
+ body.appendString("--\(boundary)\r\n")
248
+
249
+ body.appendString("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n")
250
+
251
+ body.appendString("\(value)\r\n")
252
+
253
+ }
254
+
255
+ }
256
+
257
+ let filename = "user-profile.jpg"
258
+
259
+ let mimetype = "image/jpg"
260
+
261
+ body.appendString("--\(boundary)\r\n")
262
+
263
+ body.appendString("Content-Disposition: form-data; name=\"\(filePathKey!)\"; filename=\"\(filename)\"\r\n")
264
+
265
+ body.appendString("Content-Type: \(mimetype)\r\n\r\n")
266
+
267
+ body.appendData(imageDataKey)
268
+
269
+ body.appendString("\r\n")
270
+
271
+ body.appendString("--\(boundary)--\r\n")
272
+
273
+ return body
274
+
275
+ }
276
+
277
+ func generateBoundaryString() -> String {
278
+
279
+ return "Boundary-\(NSUUID().UUIDString)"
280
+
281
+ }
282
+
283
+ //カメラで写真を取る
284
+
285
+ func pickImageFromCamera() {
286
+
287
+ if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera) {
288
+
289
+ let controller = UIImagePickerController()
290
+
291
+ controller.delegate = self
292
+
293
+ controller.sourceType = UIImagePickerControllerSourceType.Camera
294
+
295
+ self.presentViewController(controller, animated: true, completion: nil)
296
+
297
+ }
298
+
299
+ }
300
+
301
+
302
+
303
+ //写真をライブラリから選択
304
+
305
+ func pickImageFromLibrary() {
306
+
307
+ if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.PhotoLibrary) {
308
+
309
+ let controller = UIImagePickerController()
310
+
311
+ controller.delegate = self
312
+
313
+ controller.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
314
+
315
+ self.presentViewController(controller, animated: true, completion: nil)
316
+
317
+ }
318
+
319
+ }
320
+
321
+ //画像が選択されたら呼び出される
322
+
323
+ func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
324
+
325
+ if info[UIImagePickerControllerOriginalImage] != nil {
326
+
327
+ let image = info[UIImagePickerControllerOriginalImage] as! UIImage
328
+
329
+ //iamgeForUploadというUIImageを用意しておいてそこに一旦預ける
330
+
331
+ self.imageForUpload.image = image
332
+
333
+ self.myImageUploadRequest()
334
+
335
+ }
336
+
337
+ picker.dismissViewControllerAnimated(true, completion: nil)
338
+
339
+ }
340
+
341
+ }
342
+
343
+ ```
344
+
345
+
346
+
347
+ `upload.php`
348
+
349
+
350
+
351
+ ```php
352
+
353
+ <?php
354
+
355
+ $userId = $_POST["userId"];
356
+
357
+ //下記のディレクトリ名は好きなものでOK
358
+
359
+ $target_dir = "wp-content/uploads/2015/02";
360
+
361
+ if(!file_exists($target_dir))
362
+
363
+ {
364
+
365
+ mkdir($target_dir, 0777, true);
366
+
367
+ }
368
+
369
+
370
+
371
+ $target_dir = $target_dir . "/" . basename($_FILES["file"]["name"]);
372
+
373
+
374
+
375
+ if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_dir)) {
376
+
377
+ echo json_encode([
378
+
379
+ "Message" => "The file ". basename( $_FILES["file"]["name"]). " has been uploaded.",
380
+
381
+ "Status" => "OK",
382
+
383
+ "userId" => $_POST["userId"]
384
+
385
+ ]);
386
+
387
+
388
+
389
+ } else {
390
+
391
+
392
+
393
+ echo json_encode([
394
+
395
+ "Message" => "Sorry, there was an error uploading your file.",
396
+
397
+ "Status" => "Error",
398
+
399
+ "userId" => $_POSt["userId"]
400
+
401
+ ]);
402
+
403
+ }
404
+
405
+ ?>
406
+
407
+ ```
408
+
409
+