gpt4 book ai didi

java - 使用 AngularJS 和 Java Spring 发布表单数据

转载 作者:行者123 更新时间:2023-12-01 11:07:32 25 4
gpt4 key购买 nike

我有一个jsp文件,我正在其中上传文件。为了文件的后端处理,我在 Spring 制作了一个 Controller 。但它在控制台中返回错误:字符串参数“名称”不存在?我的代码是 -

JSP 文件

<input class="fileInput" type="file" id="fileInput" accept="image/gif, image/jpeg, image/png" />
<button type="button" ng-click="saveProfile()">Update</button>

JS文件

$scope.username = 01238339595;
$scope.saveProfile = function() {
var input = document.getElementById('fileInput');
if (input.files && input.files[0]) {
var formData = new FormData();
formData.append("name", $scope.username);
formData.append("file", input.files[0]);
console.log("form data " + formData);
$http.post("save-avatar", formData)
.success(function(data, status, headers,config) {
console.log('Success');
})
.error(function(data, status, headers, config) {
console.log('Error');
});
}
};

Controller

@RequestMapping(value = "save-avatar", method = RequestMethod.POST)
public String handleFormUpload(@RequestParam("name") String name, @RequestParam("file") MultipartFile file,
HttpServletRequest request) throws IOException {
if (file.isEmpty())
throw new IOException("File Field is Empty");

ServletContext servletContext = request.getSession().getServletContext();
String absoluteDiskPath = servletContext.getRealPath("/");

File folder = new File(absoluteDiskPath + "/avatar/");
if (!folder.exists())
folder.mkdirs();

File avatarFile = new File(folder, name + ".jpg");
if (!avatarFile.exists())
avatarFile.createNewFile();

FileOutputStream outputStream = null;
try {
outputStream = new FileOutputStream(avatarFile);
outputStream.write(file.getBytes());
} finally {
if (outputStream != null)
outputStream.close();
}

return "redirect:/avatar-profile?name=" + name;
}

在我的配置 xml 中:

<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="10485760" />
</bean>

最佳答案

不要使用上面的 Controller 方法,请使用以下方法:

@RequestMapping(value = "/save-avatar", method = RequestMethod.POST)
public void UploadFile(MultipartHttpServletRequest request, HttpServletResponse response) {

Iterator<String> itr = request.getFileNames();
MultipartFile file=null;

while (itr.hastNext()) {
file = request.getFile(itr.next());
String name = request.getParameter("name");

//Do your stuff here.......
}
}

关于java - 使用 AngularJS 和 Java Spring 发布表单数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32789988/

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