play框架之文件上传

本文介绍了如何在Play Framework 2.3.x中处理文件上传,通过定义routes路由`post /upload.do controllers.xxx.upload`来实现后台文件上传功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<span style="font-size:18px;"><!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
    <form action="/upload.do" method="POST" enctype="multipart/form-data">
        <input type="file" name="myfile">
        <input type="submit"/>
    </form>
</body>
</html></span>

routes路由表 post    /upload.do      controllers.xxx.upload

后台实现:

<span style="font-size:18px;">public static Result upload() throws IOException{
		MultipartFormData body = request().body().asMultipartFormData();
		  FilePart filepart = body.getFile("myfile");
		  if (filepart != null) {
		    String fileName = filepart.getFilename();
		    String contentType = filepart.getContentType(); 
		    File file = filepart.getFile();//获取到默认上传保存的完整文件路径,这只是个临时文件
		    BufferedInputStream is=new BufferedInputStream(new FileInputStream(file));
		    File newFile=new File("e://upload/"+filepart.getFilename());//要保存的文件路径
		    BufferedOutputStream os=new BufferedOutputStream(new FileOutputStream(newFile));
		    byte[] b = new byte[1024]; 
		    while(is.read(b)!=-1){
		    	os.write(b);
		    }
		    is.close();
		    os.close();
		    return ok("File uploaded");
		  } else {
		    flash("error", "Missing file");
		    
		    return ok("aa");    
		  }
	}</span>


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值