如何获取上传文件的相对路径作为变量在PHP(转贴)(How to get relative path of uploaded file as variable in php (repost))
我怎样才能获得我上传文件的相对路径? 例如,如果我上传test.png,我会得到/upload/test.png。 这是我的HTML:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Jquery Ajax File Upload</title> </head> <body> <div class="col-sm-6"> <div class="form-group "> <label>Profile image</label> <div class="input-group"> <span class="input-group-addon"><i class="fa fa-image"></i></span> <input type="text" class="form-control" name="profile_image" autocomplete="off" value="" placeholder="" > <label class="btn btn-default btn-file input-group-addon"> Browse <input type="file" name="image" style="display: none;" onchange="myFunction()" id="image" > </label> <div class="result"></div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> <script> $('#image').change(function(e){ var file = this.files[0]; var form = new FormData(); form.append('image', file); $.ajax({ url : "http://192.168.1.147/upload.php", type: "POST", cache: false, contentType: false, processData: false, data : form, success: function(response){ $('.result').html(response.html) } }); }); </script> </div> </div> </div> </body> </html>
PHP:
<?php $file = $_FILES['image']; /* Allowed file extension */ $allowedExtensions = ["gif", "jpeg", "jpg", "png", "svg"]; $fileExtension = explode(".", $file["name"]); /* Contains file extension */ $extension = end($fileExtension); /* Allowed Image types */ $types = ['image/gif', 'image/png', 'image/x-png', 'image/pjpeg', 'image/jpg', 'image/jpeg','image/svg+xml']; if(in_array(strtolower($file['type']), $types) // Checking for valid image type && in_array(strtolower($extension), $allowedExtensions) // Checking for valid file extension && !$file["error"] > 0) // Checking for errors if any { if(move_uploaded_file($file["tmp_name"], 'uploads/'.$file['name'])){ header('Content-Type: application/json'); echo json_encode(['html' => /*return uploded file path and name*/ ]); echo $_FILES['upload']['name']; }else{ header('Content-Type: application/json'); echo json_encode(['html' => 'Unable to move image. Is folder writable?']); } }else{ header('Content-Type: application/json'); echo json_encode(['html' => 'Please upload only png, jpg images']); } ?>
代码起作用,即上传文件,但我不知道如何恢复路径。 该路径可能会因用户配置文件图像而改变,稍后我会将上传路径更改为/ $ username。 如果您知道如何获取名称,请将其发布。 提前致谢。
How can I get the relative path to my uploaded file? For example if I upload test.png I would get /upload/test.png. Here is my HTML:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Jquery Ajax File Upload</title> </head> <body> <div class="col-sm-6"> <div class="form-group "> <label>Profile image</label> <div class="input-group"> <span class="input-group-addon"><i class="fa fa-image"></i></span> <input type="text" class="form-control" name="profile_image" autocomplete="off" value="" placeholder="" > <label class="btn btn-default btn-file input-group-addon"> Browse <input type="file" name="image" style="display: none;" onchange="myFunction()" id="image" > </label> <div class="result"></div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> <script> $('#image').change(function(e){ var file = this.files[0]; var form = new FormData(); form.append('image', file); $.ajax({ url : "http://192.168.1.147/upload.php", type: "POST", cache: false, contentType: false, processData: false, data : form, success: function(response){ $('.result').html(response.html) } }); }); </script> </div> </div> </div> </body> </html>
PHP:
<?php $file = $_FILES['image']; /* Allowed file extension */ $allowedExtensions = ["gif", "jpeg", "jpg", "png", "svg"]; $fileExtension = explode(".", $file["name"]); /* Contains file extension */ $extension = end($fileExtension); /* Allowed Image types */ $types = ['image/gif', 'image/png', 'image/x-png', 'image/pjpeg', 'image/jpg', 'image/jpeg','image/svg+xml']; if(in_array(strtolower($file['type']), $types) // Checking for valid image type && in_array(strtolower($extension), $allowedExtensions) // Checking for valid file extension && !$file["error"] > 0) // Checking for errors if any { if(move_uploaded_file($file["tmp_name"], 'uploads/'.$file['name'])){ header('Content-Type: application/json'); echo json_encode(['html' => /*return uploded file path and name*/ ]); echo $_FILES['upload']['name']; }else{ header('Content-Type: application/json'); echo json_encode(['html' => 'Unable to move image. Is folder writable?']); } }else{ header('Content-Type: application/json'); echo json_encode(['html' => 'Please upload only png, jpg images']); } ?>
The code works, that is upload the file but I don't know how to get the path back. The path may change because its for a user profile image and later I will change the upload path to one that is /$username. If you know how get the name only please post that anyway. Thanks in advance.
原文:https://stackoverflow.com/questions/41504769
最满意答案
如果您没有要返回的默认值,则可以返回
Option[Int]
,并将其与getOrElse
结合使用:def a(n: Int): Option[Int] = { if (n < 100) { Some(n * 2) } else { None } } a(10).getOrElse("Something else")
另一种可能性是使用部分功能 ,因为在您的情况下,您的第一个功能并不涵盖所有情况,并且您希望有一个后备:
val a: PartialFunction[Int, Int] = { case n if n < 100 => n * 2 } val b: PartialFunction[Int, String] = { case _ => "Something else" }
然后你可以使用
applyOrElse
:// If function a is not defined for the input, then call function b val result = a.applyOrElse(10, b)
或将两个部分函数合并到另一个函数中,并调用它:
// Combine a and b val cf = a.orElse(b) // Call val result = cf(10)
If you don't have a default value to return, then you could return an
Option[Int]
instead, and combine this withgetOrElse
:def a(n: Int): Option[Int] = { if (n < 100) { Some(n * 2) } else { None } } a(10).getOrElse("Something else")
Another possibility is to use partial functions, because in your case your first function does not cover all cases, and you want to have a fallback:
val a: PartialFunction[Int, Int] = { case n if n < 100 => n * 2 } val b: PartialFunction[Int, String] = { case _ => "Something else" }
Then you can use
applyOrElse
:// If function a is not defined for the input, then call function b val result = a.applyOrElse(10, b)
or combine both partial functions into another function, and call that one:
// Combine a and b val cf = a.orElse(b) // Call val result = cf(10)
相关问答
更多-
下列中不属于面向对象的编程语言的是?[2022-05-30]
a -
在Scala返回(Return in Scala)[2023-08-16]
它不像只是省略return关键字那么简单。 在Scala中,如果没有return那么最后一个表达式将被视为返回值。 所以,如果最后一个表达式是你想要返回的,那么你可以省略return关键字。 但是如果你想要返回的不是最后的表达式,那么Scala 就不会知道你想要返回 。 一个例子: def f() = { if (something) "A" else "B" } 这里函数f的最后一个表达式是一个if / else表达式,它计算为一个String。 因为没有明确的return标记, ... -
你有三个选择: (A)从join中删除参数类型C,因为返回值总是String : def join[K,A,B](custs:Map[K,A],txns:Map[K,B]) :Map[K, String]= { for((k,va) <- custs; vb <- txns.get(k)) yield k -> va.toString()+"|"+ vb.toString() } (B)添加通用组合器函数并保持方法参数化: def join[K,A,B, C](custs:Map[K,A],txn ...
-
如果您没有要返回的默认值,则可以返回Option[Int] ,并将其与getOrElse结合使用: def a(n: Int): Option[Int] = { if (n < 100) { Some(n * 2) } else { None } } a(10).getOrElse("Something else") 另一种可能性是使用部分功能 ,因为在您的情况下,您的第一个功能并不涵盖所有情况,并且您希望有一个后备: val a: PartialFunction[Int, ...
-
如何从scala中的if-else块而不是anyVal返回Int?(How to return Int from an if-else block instead of anyVal in scala?)[2023-11-08]
阅读完评论后,我相信你想要的是在blockNumber存储一个Option[Int] : val blockNumber = if (x.getName == "NATIVE") { Some(0) } else if (x.getName == "DATIVE") { Some(1) } else { None } new setBlockNumber(blockNumber) 我也会用match重写这个: val blockNumber = x.getName match { ... -
在Scala中同时打印和返回值的习惯性方式[复制链接](Idiomatic way of print and return value at the same time in Scala [duplicate])[2023-04-17]
Ruby中的Object#tap #tap基本上是K combinator的变种。 我不相信在Scala标准库中有一个实现,但是很容易添加自己的: implicit class TapExtension[T](o: => T) { def tap(f: T => Unit) = { f(o); o } } 注意:这是一个隐式转换,它不是猴子修补。 然后,你可以像这样使用它: Seq(1,2,3) .map(_ * 2) .tap(println) .foldLeft(0)(_ + _) ... -
def this_= { print("hello") } 您似乎认为这是与{ print("hello") }相等的方法this_ 。 相反,这是this_=方法,它使用过程样式声明(即不等号)。 它最常用的是这样的: scala> class A { | private var _x = "" | def x = _x | def x_=(s: String) = _x = s.toUpperCase | } defined class A sca ...
-
M.Odersky,L. Spoon和B.Venners在“Programming in Scala”中解释了这种行为。 我有第一版和7.5节(第128页)说: 值得注意的是,Scala的行为不同于Java只是因为Java的try-finally不会带来价值。 和Java一样,如果finally子句包含一个显式的return语句,或者引发一个异常,那么返回值或异常将“覆盖”之前发生在try块或其catch子句之一的任何一个。 例如,给出: def f(): Int = try { return 1 } fi ...
-
scala隐式返回值问题(scala implicit return value issue)[2023-10-15]
那是因为它适用于(w)而不是整个表达式。 尝试这个: val value = (s ==>(w)).get That's because it applies get to (w) rather than to the whole expression. Try this: val value = (s ==>(w)).get -
陈述的顺序在这里很重要。 def decode(list :List[(Int, String)]):List[String] = { def excuteDecode(list:List[(Int,String)],result:List[String]):List[String] = list match { case Nil => Nil case x::Nil=>outputCharWithTime(x._1,x._2,result) case x::y =>excut ...