我使用Play框架开发了Web服务。我在Play框架中创建了POST休息服务,如下所示。
在路线档案中
POST /imageUpload controllers.Application.imageUpload()
在Application.java中:
public static Result imageUpload() {
ObjectNode result = Json.newObject();
MultipartFormData body = request().body().asMultipartFormData();
FilePart file = body.getFile("file");
File trainImg = file.getFile();
File temp = new File("/Play_Framework/temp.jpg");
trainImg.renameTo(temp);// moved the image to another folder to check the correct image.
.
.
.
return ok(result);
}
在服务中,我编写了代码来保存从请求中接收的图像。 我已经从Ajax调用了这个服务,如下所示。
在我的index.html文件中:
var formData = new FormData();
var blob = new Blob([imageData], { type: "image/jpg"});
formData.append("file", blob, "capturedImage.jpg");
$.ajax({
url: 'http://localhost:9000/imageUpload',
data: formData,
crossDomain: true,
processData: false,
contentType: false,
async: false,
cache: false,
dataType: "json",
type: 'POST',
success: function(data){
alert(data);
var responseStr = JSON.stringify(data);
alert("Response str -- "+responseStr);
}
});
当我将文件作为Multipart表单数据上传时,我可以在服务器端将其作为多部分数据接收。但它存储为" multipartBody7906599875117091855asTemporaryFile"。
如果我收到此文件的mimitype - "内容/未知"。
当我调试时,我得到了以下多部分表单数据路径" / var / folders / f3 / r3rfqfl949z5pf2cprwn95dm0000gn / T / multipartBody7906599875117091855asTemporaryFile" 。
如何将其解析为" jpg"文件?任何人都可以帮我这样做吗?
答案 0 :(得分:1)
以下对我有用:
Application.java
public class Application extends Controller {
public static Result index() {
return ok(index.render("SO answer 30229421"));
}
public static Result imageUpload() {
ObjectNode result = Json.newObject();
Http.MultipartFormData body = request().body().asMultipartFormData();
Http.MultipartFormData.FilePart file = body.getFile("file");
File trainImg = file.getFile();
File temp = new File("/tmp/temp.jpg");
trainImg.renameTo(temp); // moved the image to another folder to check the correct image.
result.put("path", temp.getAbsolutePath());
return ok(result);
}
public static Result imageDownload(String path) {
return ok(new File(path));
}
index.scala.html
@(message: String)
<html>
<body>
<h1>@message</h1>
<input type="file" id="imageData"/>
<button onclick="send()">Send image</button>
<div id="image">
</div>
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script>
function send() {
var imageData = $('#imageData')[0].files[0];
var formData = new FormData();
var blob = new Blob([imageData], { type: "image/jpg"});
formData.append("file", blob, "capturedImage.jpg");
$.ajax({
url: 'http://localhost:9000/imageUpload',
data: formData,
crossDomain: true,
processData: false,
contentType: false,
async: false,
cache: false,
dataType: "json",
type: 'POST',
success: function(data){
$('#image').html('<img src="http://localhost:9000/imageDownload?path=' + data.path + '"/>');
}
});
}
</script>
</body>
</html>
唯一的区别是,因为您没有包含imageData
值的方式,所以我使用了此版本(根据此SO answer):
var imageData = $('#imageData')[0].files[0];