我使用 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);
}
});
当我将文件作为多部分表单数据上传时,我可以在服务器端接收它作为多部分数据。但它存储为“multipartBody7906599875117091855asTemporaryFile”。
如果我得到这个文件的mimitype - “内容/未知”。
当我调试时,我得到了以下多部分表单数据路径“/var/folders/f3/r3rfqfl949z5pf2cprwn95dm0000gn/T/multipartBody7906599875117091855asTemporaryFile”。
如何将其解析为“jpg”文件?谁能帮我做到这一点?
最佳答案
以下内容对我有用:
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];
关于java - Play Framework - Ajax Web服务调用图像请求问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30229421/