AngularJS上传文件
发布时间:2020-12-17 10:30:40 所属栏目:安全 来源:网络整理
导读:使用 AngularJS 上传文件 前台是 Angular 页面 后台使用 SpringBoot/SpirngMVC 上传文件 html div input id = "fileUpload" type = "file" / button ng-click = "uploadFile()" 上传 / button / div js $scope .upload = function () { var form = new FormD
上传文件
<div>
<input id="fileUpload" type="file" />
<button ng-click="uploadFile()">上传</button>
</div>
$scope.upload = function(){
var form = new FormData();
var file = document.getElementById("fileUpload").files[0];
fd.append('file',file);
$http({
method: 'POST',url: '/upload',data: form,headers: {'Content-Type': undefined},transformRequest: angular.identity
}).success(function (data) {
console.log('upload success');
}).error(function (data) {
console.log('upload fail');
})
}
@RequestMapping("/upload")
public void uploadFile(@RequestParam(value = "file",required = true) MultipartFile file) {
//deal with file
}
上传文件的同时传递其他参数
<div>
<input id="fileUpload" type="file" />
<button ng-click="ok()">上传</button><br>
<input ng-model="user.username" />
<input ng-model="user.password" />
</div>
$scope.ok = function () {
var form = new FormData();
var file = document.getElementById("fileUpload").files[0];
var user =JSON.stringify($scope.user);
form.append('file',file);
form.append('user',user);
$http({
method: 'POST',url: '/addUser',transformRequest: angular.identity
}).success(function (data) {
console.log('operation success');
}).error(function (data) {
console.log('operation fail');
})
};
@RequestMapping("/upload")
public Map<String,Object> upload(@RequestParam(value = "file") MultipartFile file,@RequestParam(value = "user",required = true) String user) {
try (FileInputStream in = (FileInputStream) headImg.getInputStream();
FileOutputStream out = new FileOutputStream("filePathAndName")) {
//将Json对象解析为UserModel对象
ObjectMapper objectMapper = new ObjectMapper();
UserModel userModel = objectMapper.readValue(user,UserModel.class);
//保存文件到filePathAndName
int hasRead = 0;
byte[] bytes = new byte[1024];
while ((hasRead = in.read(bytes)) > 0) {
out.write(bytes,0,hasRead);
}
} catch (IOException e) {
e.printStackTrace();
}
}
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- angularjs:在select元素中调用一个函数
- 有没有办法使AngularJS负载分支在开始,而不是在需要时?
- angularjs – 从Angular 2组件中的CDN加载css
- Exception message: /bin/bash: line 0: fg: no job contro
- 为什么我的Angular2开发服务器和生成版本的CSS看起来不同?
- WebService - SOAP协议
- unix – grep如何运行这么快?
- webservice+ejb3+jboss4.2.3问题:setProperty must be over
- Angular 2单选按钮无法使用反应形式正确初始化
- 将Scala @suspendable方法转换为未来