我最近创建了一个HTTP触发的Java Azure函数来处理一些后端任务。 Azure功能的主要目的是接受/读取包装在javascript FormData对象中的图像文件并将文件上传到我的azure blob存储。
我一直在网上搜索,但找不到如何从Java中的FormData对象读取文件的有效示例?我已经看到了一些使用C#和node.js。
这里是链接-> Azure functions - How to read form data
所以必须要用Java来做到这一点,有人能提供一个可行的例子吗?
public class Function {
@FunctionName("HttpTrigger-Java")
public HttpResponseMessage run(@HttpTrigger(name = "req", methods =
{HttpMethod.POST}) HttpRequestMessage<Optional<String>> request,
final ExecutionContext context) {
String postRequest = request.getBody();
//HELP: I need to get the FormData object from the postRequest some how...
FormData formDataObj = postRequest.getFormData();
//HELP: Then I need to get my image file from the FormData Object...
File sourceFile = formDataObj.getImageFile();
try {
// Parse the connection string
storageAccount = CloudStorageAccount.parse(storageConnectionString);
// get blob client
blobClient = storageAccount.createCloudBlobClient();
// get container name
container = blobClient.getContainerReference(containerName);
//Getting a blob reference
blob = container.getBlockBlobReference(sourceFile.getName());
//Creating blob and uploading file to it
blob.uploadFromFile(sourceFile.getAbsolutePath());
} catch (StorageException ex) {
return request.createResponseBuilder(HttpStatus.BAD_REQUEST).body("There was an error with Storage Account.").build();
}
return request.createResponseBuilder(HttpStatus.OK).body("Images Uploaded Successfully!, ").build();
}
}
我相信您可以使用Apache Commons FileUpload解析正文,并通过字符串进行解析,此answer显示了一种实现方法。