[英]How to send file using javascript
我正在尝试制作一个需要上传文件的上传页面。 我在这里使用 Spring 框架,我的查询位于上传按钮上,我正在调用一个 JavaScript 方法,该方法应该使用 jQuery AJAX 将我的文件发送到控制器。 有没有办法通过 JavaScript 传递它?
以下是我正在尝试的代码。
<body>
<div style="text-align: center; margin-top: 60px;">
<form enctype="multipart/form-data">
Select file:
<input type="file" name="dataFile" id="fileAttachment"/><br/><br/>
<div style="text-align: center; margin-top: 100px;">
<input style="cursor: pointer;" onmouseover="" onclick="uploadAttachment()" class="dialogbox" type="submit" value="Upload Report" />
</div>
</form>
</div>
</body>
JS:
<script language="Javascript">
function uploadAttachment(){
var Name = jQuery('#Name option:selected').text();
jQuery.post('upload',{Name:Name}
function(data){
if(data==1)
alert("success");
else
alert("failed");
});
}
</script>
在controller.java页面下面是写的代码
@RequestMapping(value = "upload", method=RequestMethod.POST)
public @ResponseBody String upload(HttpServletRequest request, HttpServletResponse response,
@RequestParam("Name") String Name){
System.out.println(Name);
}
如果您实际上正在寻找一种纯粹的 javascript 方式来上传图像/文件,那么以下 2009 年的教程将告诉您如何做到这一点:
http://igstan.ro/posts/2009-01-11-ajax-file-upload-with-pure-javascript.html
当我想向表单提交添加基本身份验证而不启用 cookie 时,我遇到了这个问题。 例如,当您有包含文件名、文件等字段的用户名/密码字段时。
希望这可以帮助!
我认为您可以尝试使用以下代码使用 javascript 上传文件。
function uploadAttachment(){
$('#fileAttachment').trigger('click');
if (typeof timer != 'undefined') {
clearInterval(timer);
}
timer = setInterval(function() {
if ($('#fileAttachment').val() != '') {
clearInterval(timer);
$.ajax({
url: 'YOUR_UPLOAD_URL',
type: 'post',
dataType: 'json',
data: new FormData($('#fileAttachment').closest('form')[0]),
cache: false,
contentType: false,
processData: false,
success: function(response){
}
});
}
}, 500);
}
您需要将YOUR_UPLOAD_URL
替换为您的服务器上传 URL。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.