gpt4 book ai didi

java - 无法通过java和postman的多部分表单数据上传文件

转载 作者:太空宇宙 更新时间:2023-11-04 10:27:05 25 4
gpt4 key购买 nike

我一直在尝试从java和postman上传文件。但我无法上传。服务器返回响应 200 Ok。但是,该文件尚未上传。API详细信息:我有一个用于上传文件的 API 作为“FileExplorerController”。该 API 有一个方法“upload()”来上传文件。访问此方法的 URL 为“/fileupload”。如果我通过 HTML UI 上传文件,API 工作正常。但我正在尝试使用 Java 上传。我也尝试过使用 postman 。我已经通过多种方式传递了多部分表单数据。但无法解决问题。代码如下。

API - 上传 - 功能

    public Result upload() {
String fileName="";
String folderPath="";
String fileDescription="";
String userName = "";
StopWatch stopWatch = null;
List<FileUploadStatusVo> fileStatus = new ArrayList<>();
try {
stopWatch = LoggerUtil.startTime("FileExplorerController -->
upload() : File Upload");
StringBuilder exceptionBuilder = new StringBuilder();
Http.MultipartFormData body =
play.mvc.Controller.request().body().asMultipartFormData();
Http.Context ctx = Http.Context.current();
userName = ctx.session().get(SessionUtil.USER_NAME);
String password = "";
if(StringUtils.isBlank(userName)) {
Map<String, String[]> formValues = play.mvc.Controller.
request().body().asMultipartFormData().asFormUrlEncoded();
if(formValues != null) {
if(formValues.get("userName") != null &&
formValues.get("userName").length > 0) {
userName = formValues.get("userName")[0];
}
if(formValues.get("password") != null &&
formValues.get("password").length > 0) {
password = formValues.get("password")[0];
}
}
if(StringUtils.isBlank(userName) ||
StringUtils.isBlank(password)) {
return Envelope.ok();
}
UserVo userVo = userService.findUserByEmail(userName);
boolean success = BCrypt.checkpw(password, userVo.password);
if(!success) {
return badRequest("Password doesn't match for the given user
name: "+userName);
}
if(userVo == null) {
return Envelope.ok();
}
}
boolean override = false;
String fileTags="";
boolean isPublicView = false;
boolean isPublicDownload = false;
boolean isPublicDelete = false;

boolean isEmailNotification = false;
boolean isEmailWithS3Link = false;

List<String> viewerGroupNames = new ArrayList<>();
List<String> downloaderGroupNames = new ArrayList<>();
List<String> deleterGroupNames = new ArrayList<>();

List<String> viewerUserNames = new ArrayList<>();
List<String> downloaderUserNames = new ArrayList<>();
List<String> deleterUserNames = new ArrayList<>();

List<String> emailIds = new ArrayList<>();

Map<String, String[]> formValues =
play.mvc.Controller.request().body().
asMultipartFormData().asFormUrlEncoded();

JSONObject obj = new JSONObject(formValues.get("model")[0]);

Set<String> groupNames = new HashSet<>();
Set<String> userNames = new HashSet<>();

if(obj != null) {
if(obj.get("override") != null) {
override = Boolean.valueOf(obj.get("override").toString());
}
if(obj.get("description") != null) {
fileDescription = obj.get("description").toString();
}
if(obj.get("tags") != null) {
fileTags = obj.get("tags").toString();
}

if(obj.get("folderPath") != null){
folderPath = obj.get("folderPath").toString();
} else {
folderPath =
ctx.session().get(SessionUtil.LOCAL_STORAGE_PATH);
}


if(obj.get("isPublicView") != null) {
isPublicView =
Boolean.parseBoolean(obj.get("isPublicView").toString());
}

if(obj.get("isPublicDownload") != null) {
isPublicDownload =
Boolean.parseBoolean(obj.get("isPublicDownload").toString());
}

if(obj.get("isPublicDelete") != null) {
isPublicDelete = Boolean.parseBoolean(
obj.get("isPublicDelete").toString());
}

if(obj.get("emailNotification") != null) {
isEmailNotification =
Boolean.parseBoolean(obj.get("emailNotification").toString());
}

if(obj.get("emailWithFileAttachement") != null) {
isEmailWithS3Link =
Boolean.parseBoolean(obj.get(
"emailWithFileAttachement").toString());
}

if(obj.get("viewerGroupNames") != null) {
//TODO
if(!isPublicView) {
String[] namesArr =
(obj.get("viewerGroupNames").toString()).split(",");
for(String name:namesArr) {
if(StringUtils.isNotEmpty(name)) {
viewerGroupNames.add(name);
groupNames.add(name);
}
}
}
}

if(obj.get("downloaderGroupNames") != null) {
//TODO
if(!isPublicDownload) {
String[] namesArr =
(obj.get("downloaderGroupNames").toString().split(","));
for(String name:namesArr){
if(StringUtils.isNotEmpty(name)) {
downloaderGroupNames.add(name);
groupNames.add(name);
}
}
}
}

if(obj.get("deleteGroupNames") != null) {
//TODO
if(!isPublicDelete){
String[] namesArr =
(obj.get("deleteGroupNames").toString().split(","));
for(String name:namesArr){
if(StringUtils.isNotEmpty(name)) {
deleterGroupNames.add(name);
groupNames.add(name);
}
}
}
}

if(obj.get("viewerUserNames") != null) {
//TODO
if(!isPublicView) {
String[] namesArr =
(obj.get("viewerUserNames").toString()).split(",");
for(String name:namesArr) {
if(StringUtils.isNotEmpty(name)) {
viewerUserNames.add(name);
userNames.add(name);
}
}
}
}
if(obj.get("downloaderUserNames") != null) {
//TODO
if(!isPublicDownload) {
String[] namesArr =
(obj.get("downloaderUserNames").toString().split(","));
for(String name:namesArr){
if(StringUtils.isNotEmpty(name)) {
downloaderUserNames.add(name);
userNames.add(name);
}
}
}
}
if(obj.get("deleteUserNames") != null) {
//TODO
if(!isPublicDelete){
String[] namesArr =
(obj.get("deleteUserNames").toString().split(","));
for(String name:namesArr){
if(StringUtils.isNotEmpty(name)) {
deleterUserNames.add(name);
userNames.add(name);
}
}
}
}

if(obj.get("emailIds") != null) {
if(isEmailWithS3Link) {
String[] emailIdsArr =
(obj.get("emailIds").toString()).split(",");
for(String emailId:emailIdsArr){
if(StringUtils.isNotEmpty(emailId)){
emailIds.add(emailId);
}
}
}
}
}

if(groupNames.size() == 0 && userNames.size() == 0){
isEmailNotification = false;
}

List<Http.MultipartFormData.FilePart> files = body.getFiles();
boolean multiUpload = false;
if(files != null && files.size() > 1) {
multiUpload = true;
}
Logger.info("Total Number of files is to be uploaded:"+ files.size()
+" by user: " + userName);
int uploadCount = 0;
List<String> fileNames = new ArrayList<>();
List<String> fileMasters = new ArrayList<>();
FileMasterVo fileMasterVo = null;
UserVo userVo = userService.findUserByEmail(userName);
for(Http.MultipartFormData.FilePart uploadedFile: files) {
if (uploadedFile == null) {
return badRequest("File upload error for file " +
uploadedFile + " for file path: " + fileName);
}
uploadCount++;
String contentType = uploadedFile.getContentType();
String name = uploadedFile.getFile().getName();
Logger.info("Content Type: " + contentType);
Logger.info("File Name: " + fileName);
Logger.info("Name: " + name);
Logger.info("Files Processed : "+uploadCount+"/"+files.size()+"
for user: "+userName);
try {
String extension =
FileUtil.getExtension(uploadedFile.getFilename()).toLowerCase();
File renamedUploadFile =

FileUtil.moveTemporaryFile(System.getProperty("java.io.tmpdir"),
System.currentTimeMillis() + "_" +
uploadedFile.getFilename(), uploadedFile.getFile());
FileInputStream fis = new
FileInputStream(renamedUploadFile);
String errorMsg = "";
fileName = folderPath + uploadedFile.getFilename();
fileNames.add(uploadedFile.getFilename());
if(multiUpload) {
Logger.info("Attempting to upload file " + folderPath +
"/" + uploadedFile.getFilename());
fileMasterVo = fileService.upload(folderPath,fileName,
fileDescription, new Date(), fis, fis.available(),
extension, override,
fileTags, isPublicView, isPublicDownload,
isPublicDelete, viewerGroupNames, downloaderGroupNames,
deleterGroupNames, viewerUserNames,
downloaderUserNames,
deleterUserNames,userName,isEmailNotification);
} else if(fileName != null) {
Logger.info("Attempting to upload file " + fileName);
int index = fileName.lastIndexOf("/");
if (index > 1) {
fileMasterVo =
fileService.upload(folderPath,fileName, fileDescription,
new Date(), fis, fis.available(), extension, override,
fileTags, isPublicView, isPublicDownload,
isPublicDelete, viewerGroupNames, downloaderGroupNames,
deleterGroupNames, viewerUserNames,
downloaderUserNames,
deleterUserNames,userName,isEmailNotification);
} else {
errorMsg = "Root Folder MUST exist to upload any
file";
return badRequest(errorMsg);
}
} else {
errorMsg = "File Name is incorrect";
return badRequest(errorMsg);
}
createFileActivityLog(
fileMasterVo,userVo,ViewConstants.UPLOADED);
if (fileMasterVo != null && fileMasterVo.getId() != null) {
fileMasters.add(fileMasterVo.getId().toString());
}

} catch (Exception inEx) {
createErrorLog(userName,fileName,inEx);
exceptionBuilder.append("Exception occured in uploading
file: ");
exceptionBuilder.append(name);
exceptionBuilder.append(" are as follows ");
exceptionBuilder.append(ExceptionUtils.getStackTrace(inEx));
}
fileStatus.add(new
FileUploadStatusVo(uploadedFile.getFilename(),
fileMasterVo.getStatus()));
}

if(isEmailNotification){
fileService.sendNotificationForFile(folderPath,fileNames,
userName, groupNames,
userNames, ViewConstants.UPLOADED);
}

if (isEmailWithS3Link) {
//fileService.sendFileS3Link(folderPath, emailIds, fileMasters);
// Replacing sending S3 link with sending cdi specific link
fileService.sendFilesLink(emailIds, fileMasters);
}
String exceptions = exceptionBuilder.toString();
LoggerUtil.endTime(stopWatch);
if(!StringUtils.isBlank(exceptions)) {
Logger.error("Exception occured while uploading file: " +
fileName + " are as follows " + exceptions);
}
return Envelope.ok(fileStatus);
} catch (Exception inEx) {
createErrorLog(userName,fileName,inEx);
return badRequest("There is a system error please contact
support/administrator" );
} }

客户端

**Client - Program**
multipart.addFormField("fileName",file.getAbsolutePath());
multipart.addFormField("folderPath","D/");
multipart.addFormField("fileDescription","Desc");
multipart.addFormField("userName","superadmin");
multipart.addFormField("password","admin");
multipart.addFormField("override","false");
multipart.addFormField("fileTags","tag");
multipart.addFormField("isPublicView","true");
multipart.addFormField("isPublicDownload","true");
multipart.addFormField("isPublicDelete","false");
multipart.addFormField("isEmailNotification","false");
multipart.addFormField("isEmailWithS3Link","true");*/


multipart.addFormField("file", input);
System.out.print("SERVER REPLIED: ");

for (String line : response)
{
System.out.print(line);
}
// synchronize(clientFolder, uploadFolder, true);

}
catch (MalformedURLException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}

最佳答案

我可以使用以下代码片段上传。

这里的“model”是一个包含所有参数的json对象。

DefaultHttpClient client = new DefaultHttpClient();
HttpEntity entity = MultipartEntityBuilder
.create()
.addTextBody("userName", userName)
.addTextBody("password", passWord)
.addBinaryBody("upload_file", new File(sourceFolder + "/" + fileName), ContentType.create("application/octet-stream"), fileName)
.addTextBody("model", object.toString())
.build();
HttpPost post = new HttpPost(uploadURL);
post.setEntity(entity);
HttpResponse response = null;
try {
response = client.execute(post);
if (response.getStatusLine().getStatusCode() == 200) {
logger.info("File " + file.getName() + " Successfully Uploaded At: " + destination);
} else {
logger.info("File Upload Unsuccessful");
}
logger.info("Response from server:" + response.getStatusLine());

} catch (ClientProtocolException e) {
logger.error("Client Protocol Exception");
logger.error(e.getMessage());

关于java - 无法通过java和postman的多部分表单数据上传文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50412441/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com