http://demo.dcloud.net.cn/helloh5/uploader/upload.php文件是怎么实现上传的,它的具体代码谁有!
- 发布:2014-10-21 14:23
- 更新:2019-10-25 10:13
- 阅读:46333
这个代码非常简单,你可以参考下:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$ret=array('strings'=>$_POST,'error'=>'0');
$fs=array();
foreach ( $_FILES as $name=>$file ) {
$fn=$file['name'];
$ft=strrpos($fn,'.',0);
$fm=substr($fn,0,$ft);
$fe=substr($fn,$ft);
$fp='files/'.$fn;
$fi=1;
while( file_exists($fp) ) {
$fn=$fm.'['.$fi.']'.$fe;
$fp='files/'.$fn;
$fi++;
}
move_uploaded_file($file['tmp_name'],$fp);
$fs[$name]=array('name'=>$fn,'url'=>$fp,'type'=>$file['type'],'size'=>$file['size']);
}
$ret['files']=$fs;
echo json_encode($ret);
}else{
echo "{'error':'Unsupport GET request!'}";
}
?>
给你们贡献一个.net后台的上传
public IHttpActionResult Post()
{
if (!Request.Content.IsMimeMultipartContent()) //如果不是文件类型 直接返回
{
return Ok();
}
var provider = new MultipartFormDataMemoryStreamProvider(); //文件流
try
{
var result = Task.Run(async () => await Request.Content.ReadAsMultipartAsync(provider)).Result;
string serviceCode = result.FormData.GetValues("serviceCode").FirstOrDefault();
string userId = result.FormData.GetValues("userId").FirstOrDefault();
string feedback = result.FormData.GetValues("feedback").FirstOrDefault();
foreach (var stream in result.Contents.Where((content, idx) => result.IsStream(idx))) {
var filename = stream.Headers.ContentDisposition.FileName.Replace("\"", "");
var ms = stream.ReadAsStreamAsync().Result;
var fileStorage = FileStorageFactory.CreateFileStorage(ms, filename, stream.Headers.ContentType.MediaType);
package.FileStorages.Add(fileStorage);
}
}
catch (Exception e)
{
return BadRequest();
}
return Ok("success");
}
public class MultipartFormDataMemoryStreamProvider : MultipartMemoryStreamProvider {
private readonly Collection<bool> _isFormData = new Collection<bool>();
private readonly NameValueCollection _formData = new NameValueCollection(StringComparer.OrdinalIgnoreCase);
public NameValueCollection FormData {
get { return _formData; }
}
public override Stream GetStream(HttpContent parent, HttpContentHeaders headers) {
if (parent == null) throw new ArgumentNullException("parent");
if (headers == null) throw new ArgumentNullException("headers");
var contentDisposition = headers.ContentDisposition;
if (contentDisposition != null) {
_isFormData.Add(String.IsNullOrEmpty(contentDisposition.FileName));
return base.GetStream(parent, headers);
}
throw new InvalidOperationException("Did not find required 'Content-Disposition' header field in MIME multipart body part.");
}
public override async Task ExecutePostProcessingAsync() {
for (var index = 0; index < Contents.Count; index++) {
if (IsStream(index))
continue;
var formContent = Contents[index];
var contentDisposition = formContent.Headers.ContentDisposition;
var formFieldName = UnquoteToken(contentDisposition.Name) ?? string.Empty;
var formFieldValue = await formContent.ReadAsStringAsync();
FormData.Add(formFieldName, formFieldValue);
}
}
private static string UnquoteToken(string token) {
if (string.IsNullOrWhiteSpace(token))
return token;
if (token.StartsWith("\"", StringComparison.Ordinal) && token.EndsWith("\"", StringComparison.Ordinal) && token.Length > 1)
return token.Substring(1, token.Length - 2);
return token;
}
public bool IsStream(int idx) {
return !_isFormData[idx];
}
}
折腾了一晚上,终于搞定了Java版本的,具体如下:
使用了Spring的框架+Apache的FileUpload,目前实现的版本为不支持断点续传。根据本人的经验,有几点需要注意:
1调试的时候使用debug的话会出现异常,导致文件接收不正常,如果需要调试的话,用sysout输出结果查看。
2前台使用addData传输的数据只能用字符串,貌似不支持数值型和其他类型的,否则使用request.getParameter()获取不到数据。
具体代码如下:
Map<String, Object> map = new HashMap<String, Object>();
if(request.getHeader("content-type")!=null&&"application/x-www-form-urlencoded".equals(request.getHeader("content-type"))){
return null;//不支持断点续传,直接返回null即可
}
//将请求转换成
MultipartHttpServletRequest mRequest=(MultipartHttpServletRequest)request;
Enumeration<String> ps = mRequest.getParameterNames();
while(ps.hasMoreElements()){
String hname = ps.nextElement();
System.out.println(hname);
System.out.println(mRequest.getParameter(hname));
}
int eventType=0;
int reportSource=0;
double longitude=0;
double latitude=0;
if(mRequest.getParameter("eventType")!=null||!"".equals(mRequest.getParameter("eventType").trim()))
eventType= Integer.parseInt(mRequest.getParameter("eventType"));
if(mRequest.getParameter("reportSource")!=null||!"".equals(mRequest.getParameter("reportSource").trim()))
reportSource= Integer.parseInt(mRequest.getParameter("reportSource"));
String reporter= mRequest.getParameter("reporter");
String phone= mRequest.getParameter("phone");
String title= mRequest.getParameter("title");
String description= mRequest.getParameter("description");
if(mRequest.getParameter("longitude")!=null||!"".equals(mRequest.getParameter("longitude").trim()))
longitude= Double.parseDouble(mRequest.getParameter("longitude"));
if(mRequest.getParameter("latitude")!=null||!"".equals(mRequest.getParameter("latitude").trim()))
latitude= Double.parseDouble(mRequest.getParameter("latitude"));
Iterator<String> fns=mRequest.getFileNames();//获取上传的文件列表
while(fns.hasNext()){
String s =fns.next();
System.out.println(s+"==="+mRequest.getFile(s));
// System.out.println(mRequest.getFile(s));//get file success!!!!!
MultipartFile mFile = mRequest.getFile(s);
if(mFile.isEmpty()){
map.put("error", "EventAction.picture.failed");
}else{
String basePath=Constant.BASEPICUPLOADPATH;
String dPath= Constant.SDF_PARAM.format(new Date());
File dir = new File(basePath+dPath);
if(!dir.exists()){
dir.mkdirs();
}
String originFileName=mFile.getOriginalFilename();
String suffix=originFileName.split("\\.")[originFileName.split("\\.").length-1];
String base64Name=UUID.randomUUID().toString();
File file = new File(basePath+dPath,base64Name+"."+suffix);
try {
FileUtils.copyInputStreamToFile(mFile.getInputStream(),file);//存储文件
} catch (IOException e) {
e.printStackTrace();
}
}
}
//System.out.println(mRequest.getFileNames());
map.put("result", "OK");//返回结果
return map;
}
-
Struts框架的应该跟spring是一样的,都是吧HttpServletRequest转成MultipartHttpServletRequest来实现
2015-05-28 10:50
-
我也是用html5+的plus.uploader.createUpload,为什么程序一直返回是application/x-www-form-urlencoded了?MultipartHttpServletRequest这个对象也会一直报错
2015-08-05 17:38
-
HTML5+的upload会发送两次请求,第一次的请求消息头为application/x-www-form-urlencoded,第二次才是真正的文件传输,所以需要如下处理:Map<String, Object> map = new HashMap<String, Object>();
if(request.getHeader("content-type")!=null&&"application/x-www-form-urlencoded".equals(request.getHeader("content-type"))){
return null;//此处直接返回null代表不支持断点续传
}
// System.out.println(request.getHeader("content-type"));
MultipartHttpServletRequest mRequest=(MultipartHttpServletRequest)request;
//第二次请求时强制转换request
Enumeration<String> ps = mRequest.getParameterNames();
List<String> base64ParamNames=new ArrayList<String>();
while(ps.hasMoreElements()){//根据参数名称获取上传文件内容
String hname = ps.nextElement();
System.out.println(hname);
// System.out.println(mRequest.getParameter(hname));
if(hname.startsWith("uploadBase")){
base64ParamNames.add(hname);
}
}2015-08-12 13:56
-
后台输出request.getHeader("content-type")是Multipart/form-data,但是MultipartHttpServletRequest 块还是报错....
2015-11-01 23:02
-
回复 fer2005:我也是用servlet写的,前台怎么调用呢plus.uploader.createUpload,sever写什么呢,写severlet接口,却进不到severlet方法里啊
2017-03-10 15:08
简单的net后台上传操作,核心代码如下:
context.Response.ContentType = "text/plain";
string dirPath = context.Server.MapPath("~/Temp/");
if (!Directory.Exists(dirPath))
{
Directory.CreateDirectory(dirPath);
}
try
{
HttpFileCollection files = context.Request.Files;
if (files.Count > 0)
{
for (int i = 0; i < files.Count; i++)
{
HttpPostedFile file = context.Request.Files[i];
string filePath = dirPath + file.FileName + ".jpg";
file.SaveAs(filePath);
}
}
}
catch (Exception e)
{
throw e;
}
具体详见附件
雪之梦技术驿站 - 你在互联网的路上匆匆而来,雪之梦技术驿站助你满载而去
多张图片服务器只能接收到最后一张 服务器接收文件参数requesparamter(name=“file”)multipartFile file【】files 前台上传的图片key的name属性全为file
c#
string dirPath = Server.MapPath("~/Temp/");
if (!Directory.Exists(dirPath))
{
Directory.CreateDirectory(dirPath);
}
string filePath = dirPath + DateTime.Now.ToString("yyyyMMddHHmmssffff") + ".jpg";
HttpPostedFileBase file = Request.Files[0];
file.SaveAs(filePath);
后台我用的是.net写的 我通过这种方式为什么拿不到上传的文件?我通过取Request集合中的Files文件集合拿的 拿到文件数量为0
HttpFileCollection MyFilecollection = Request.Files;
int cout = MyFilecollection.Count;
MyFilecollection[0].SaveAs(Server.MapPath("~/upload/" + MyFilecollection[0].FileName));
这种方式又不是有问题啊?
我的JAVA后台代码如下:
类头部设置的上传文件属性:
/**
- RyanCai
- 上传文件属性
*/
private File picSearchfile; //上传的文件
private String picSearchfileFileName; //文件名称
private String picSearchfileContentType; //文件类型
方法体:
public void PicSelect() {
// 跨域访问设置作用域
setAccessControl();
// 获取用户输入的查询条件,并进行转码
Map<String, Object> map = new HashMap<String, Object>();
if (request.getHeader("content-type") != null
&& "application/x-www-form-urlencoded".equals(request
.getHeader("content-type"))) {
return;// 不支持断点续传,直接返回null即可
}
// 将请求转换成
String basePath = ServletActionContext.getServletContext()
.getRealPath("/files/picsearch");// 获取服务器路径
if (picSearchfile != null) {
File savefile = new File(new File(basePath), picSearchfileFileName);
if (!savefile.getParentFile().exists())
savefile.getParentFile().mkdirs();
try {
FileUtils.copyFile(picSearchfile, savefile);
} catch (IOException e) {
e.printStackTrace();
} //备份文件
}
map.put("result", "OK");// 返回结果
JSONObject json = JSONObject.fromObject(map);
outString(json.toString());
}
基本上就相当于普通的struts2文件上传处理。
task.addFile("_doc/1456976109430.jpg",{key:"file"}); //手机中的图片
这样后台接收不到请求
task.addFile("img/1456976109430.jpg",{key:"file"});//项目中的图片
这样后台接能收到请求
@fer2005,后台用你的写法出现了上面奇怪的现象,什么情况?
上传后前面会多出4行无用信息,自己处理掉后就可用了,这是我自己的处理方式,希望可以帮到大家。
File src = new File(rootPath+"\"+fileName+"."+postfix);
File tgt = new File(rootPath+"\"+fileName+"temp"+"."+postfix);
DataInputStream in = new DataInputStream(new FileInputStream(src));
DataOutputStream out = new DataOutputStream(new FileOutputStream(tgt));
String input = "";
int count = 0;
while ((input = in.readLine()) != null)
{
count++;
System.out.println(count);
if (count < 4)
{
System.out.println(input);
}
else
{
break;
}
}
byte[] buffer = new byte[1024];
int byteread = 0;
while ((byteread = in.read(buffer)) != -1)
{
out.write(buffer, 0, byteread);
}
in.close();
out.close();
FileUtil.copy(tgt.getCanonicalPath(),src.getCanonicalPath(),true) ;
tgt.delete() ;
JAVA CODE
MultiPartRequestWrapper mulReq = (MultiPartRequestWrapper) request;
File file = mulReq.getFiles("uploadImage")[0]
String filename = mulReq.getFileNames("uploadImage")[0];
HTML CODE
task.addFile(imgPath,{key:"uploadImage",name:imgname});
@RequestMapping( "/fileUpload" )
public void fileUpload(@RequestParam ("file") MultipartFile fileUpload,HttpServletRequest request,HttpServletResponse response){
SimpleDateFormat sFormat = new SimpleDateFormat("yyyyMMddhhmmss" );
String fileName = sFormat.format(Calendar.getInstance().getTime())+ new Random().nextInt(1000);
String originalFilename = fileUpload.getOriginalFilename();
fileName += originalFilename.substring(originalFilename.lastIndexOf("." ));
String dirName = request.getSession().getServletContext().getRealPath("/" )+"fileUpload" ;
double originalFilesize = request.getContentLength();//获取源文件大小
File file = new File(dirName);
InputStream inputStream = null ;
FileOutputStream outputStream = null ;
if (!file.exists()) {
file.mkdir();
}
try {
inputStream = fileUpload.getInputStream();
if (!inputStream.equals(null)){
try {
//处理存储过程
System.out.println("dirName"+dirName+"...."+"originalFilesize"+originalFilesize);
} catch (Exception e) {
e.printStackTrace();
}
}
outputStream = new FileOutputStream(dirName+"/" +fileName);
byte [] buffer = new byte[1024 * 1024];
int len=0;
while ((len=inputStream.read(buffer)) != -1){
outputStream.write(buffer, 0, len);
outputStream.flush();
}
outputStream.close();
inputStream.close();
}
catch (FileNotFoundException e){
e.printStackTrace();
}
catch (IOException e){
e.printStackTrace();
}
}
////////////////
官方的uploader.html
42行把key:f.name 改成 key:"file"就行..跟@RequestParam ("file") 里面的file要一样
task.addFile(f.path,{key:"file"});
.net 后台
接收数据 string strClient = Request["client"];
接收文件
//客户端上传的文件集合
HttpFileCollection MyFilecollection = Request.Files;
for (int i = 0; i < MyFilecollection.Count; i )
{
HttpPostedFile FileInfo = MyFilecollection[i];
//FileInfo.FileName 是文件名
//FileInfo.SaveAs(filepath); 把图片保存到服务器路径
}
有没有java的
-
回复 Allen梅川酷子:JAVA CODE
MultiPartRequestWrapper mulReq = (MultiPartRequestWrapper) request;
File file = mulReq.getFiles("uploadImage")[0]
String filename = mulReq.getFileNames("uploadImage")[0];
HTML CODE
task.addFile(imgPath,{key:"uploadImage",name:imgname});
这样就可以啊2017-08-19 16:09
-
回复 suixing:JAVA CODE
MultiPartRequestWrapper mulReq = (MultiPartRequestWrapper) request;
File file = mulReq.getFiles("uploadImage")[0]
String filename = mulReq.getFileNames("uploadImage")[0];
HTML CODE
task.addFile(imgPath,{key:"uploadImage",name:imgname});2017-08-19 16:10
冈板日川 (作者)
.net怎么实现
2014-10-21 15:32
DCloud_heavensoft
其实你用input type=file上传时,服务器怎么接收就怎么接收。你可以查下type=file时.net如何接收。
2014-10-22 03:22
山川同学
回复 DCloud_heavensoft:相同的上传代码,调用同一个nodejs服务端。为什么ios可以上传成功,安卓不行,提示连接中断。求指教
2015-04-10 16:21
飞龙在天应中网
这个代码能运行么?谁试过了?我运行不了
2015-07-02 18:43
hihay
这代码写的。。。。
2016-01-22 11:24
盗版
我想把图片压缩后再上传怎么改此代码?
2016-12-28 15:05
小资电脑
这段脚本对中文支持不友好
2018-06-27 22:55
此去经年
有没有nodejs的后台
2019-10-25 10:13