我正在尝试从视图向控制器发送字符串和图像,但是我不断收到此错误:
字符串参数'text'不存在
我尝试了一些在网上找到的解决方案,但没有一个解决了我的问题。
@RequestMapping(value = "/post-create", method = RequestMethod.POST)
@ResponseBody
public String[][] createPost(@RequestParam(value="text" ) String text,
@RequestParam(value = "photo") MultipartFile body) throws IOException {
User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
String username = user.getUsername();
com.project.agro.entities.User user1 = userService.getUserByUsername(username);
Image image = new Image(body.getBytes());
imageService.addImage(image);
Post post = new Post();
post.setAuthor(user1);
post.setText(text);
post.setImage(image);
postService.addPost(post);
post = postService.addPost(post);
List<Post> posts = new ArrayList<>();
posts.add(post);
return utilsService.arrayFill(posts, user1);
}
jQuery
$("#create-post-button").click(function (e) {
e.preventDefault();
var form = $('form')[0];
var formData = new FormData(form);
$.ajax({
url: '/post-create',
data: formData,
type: 'POST',
contentType: false,
processData: false,
success: function (data) {
$("#posts-container").prepend(concatPost(data[0]));
$("#special-alert").remove();
$("#posts-container").append('' + special_alert_no_more_posts);
document.getElementById('create-post-form').reset();
$("#characters-number").text(5000);
from += 1;
$("#create-post-button").prop("disabled", true);
}
})
});
HTML
<div id="create-post-box" class="row">
<hr class=\ "middle\">
<a id="create-post-box-href"><span id="arrow-down"
class="fa fa-angle-down"></span><span id="arrow-up"
class="fa fa-angle-up hidden"></span></a>
<div id="create-post-form-div" class="hidden">
<form enctype="multipart/form-data" id="create-post-form" method="POST">
<div class="form-group">
<div class="col-sm-12">
<textarea class="form-control" maxlength="5000" rows="5" id="post-text" name="text"></textarea>
<div id="counter">
<p id="counter-line">
<span id="characters-number">5000</span> symbols left.
</p>
</div>
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<div class="input-group">
<label class="input-group-btn"> <span class="btn btn-primary"><span class="glyphicon glyphicon-picture"></span><input id="file" type="file" style="display: none;" name="photo" accept="image/x-png,image/gif,image/jpeg" multiple>
</span>
</label> <input type="text" class="form-control" readonly>
</div>
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<button type="button" id="create-post-button" class="btn btn-primary btn-md btn-block">Post it</button>
</div>
</div>
</form>
</div>
我尝试了
@RequestParam(value="text" ,required=false)
但随后显示:
字符串参数'photo'在Multipart中不存在 缺少ServletException
答案 0 :(得分:0)
尝试使用@RequestBody MultipartFile body
代替@RequestParam(value = "photo") MultipartFile body