我有注册表单(Spring mvc 应用程序),它有一些字段以及图像上传选项,我正在通过 serialize() 函数使用 ajax 将字段值发送到 Controller
现在我想通过相同的请求发送图像,以及在将请求发送到 Controller 之前用户应该预览的用户选择的图像。所以对于预览,我将选定的图像转换为字节码并将其添加到图像标签的“src”属性
Jquery 用于图像预览
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#imagePreview').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
$("#imgInput").change(function(){
readURL(this);
});
HTML 图像和输入标签
<input name=file type="file" id="imgInput"></input>
<img id="imagePreview" src="" alt="Item Image" width="96" height="80"/>
通过上面的代码我可以得到预览。现在作为提交表单要求的一部分,我需要发送表单字段和图像,为此我正在获取图像标签的“src”属性中存在的字节码,并使用 ajax 将其与字段值一起发送
Ajax 表单提交
function saveCatalogueForm(){
var catalogValue = $("#catalogueForm").serialize();
var imageInByte =$('#imagePreview').attr('src');
/* console.log(fd) */
$.ajax({
type: "POST",
dataType : "json",
url:"../catalogue/create.action?catalogValue="+catalogValue+"&fd="+imageInByte,
success:function(response){
alert("Submited Successfully");
}
});
}
这是我的 Controller
@RequestMapping( value="/catalogue/create.action", method=RequestMethod.POST)
public @ResponseBody Long create(CatalogueBase catalogueForm,byte[] fd) throws Exception {
Long parentId = null;
System.out.println(fd);
// some logic goes hear
return parentId;
}
我想要的。
上面的代码适用于较少 kb 的图像,如 3-6 kb 不超过,如果我发送超过那个,那么我将得到错误的响应 400 错误(我在 apache server.xml 页面中将 POST 大小增加到 2mb )...?
我是在写方式还是通过任何其他方式我可以通过 ajax 发送图像......?
任何帮助都会被挪用,谢谢
最佳答案
我在这里猜测,但您似乎正在将图像数据附加到 URL,并且您遇到了类似“请求 uri 太长” 的错误。
您可能会遇到一些额外的问题,因为图像数据未转义。
尝试将您的数据作为POST
数据发送:
function saveCatalogueForm(){
var catalogValue = $("#catalogueForm").serialize();
var imageInByte = encodeURIComponent($('#imagePreview').attr('src'));
/* console.log(fd) */
$.ajax({
type: "POST",
dataType : "json",
data: "catalogValue="+catalogValue+"&fd="+imageInByte,
url:"../catalogue/create.action",
success:function(response){
alert("Submited Successfully");
}
});
}
关于javascript - 如何使用 ajax 和 jquery 将图像保存到另一个文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21012173/