I'm trying to upload a file to cloudinary. I'm stucked at how to only get parts of image from the form. It keeps on throwing exception: Invalid image file. If I remove all text inputs in the form, the uploading is successful. I guess that happens because the form also has text inside. Please help me solve this. I'm really grateful for your support. Here is my code: Form.jsp:
<form role="form" action="<c:url value="/admin/product/update"/>" method="post" enctype="multipart/form-data">
<input name="id" value="${product.id}" hidden="">
<div >
<label>Name:</label> <input value="${product.name}" name="name" />
</div>
<div >
<label>Price:</label> <input value="${product.price}" type="number" name="price" />
</div>
<div >
<label>Quantity:</label> <input value="${product.quantity}" type="number" name="quantity" />
</div>
<div >
<label>Image:</label> <input value="${product.image}" name="image" />
</div>
<div >
<label>Description </label> <br>
<textarea rows="4" cols="50" name="description" value="${product.description}" ></textarea>
</div>
<div >
<label>Category</label>
<div >
<select name="catid">
<c:forEach items="${categorylist}" var="c">
<option value="${c.id}">${c.name}</option>
</c:forEach>
</select>
</div>
</div>
<div >
<label>image</label> <input type="file" name="image" value="${product.image }" />
</div>
Servlet.java
BeanUtils.populate(product, request.getParameterMap());
//if (catid != product.getCategory().getId()) {
// Category category = new Category();
category = dao2.getCategoryByID(catid);
product.setCategory(category);
Map result = null;
Collection<Part> fileParts = request.getParts();
for (Part part : fileParts) {
String fileName = part.getSubmittedFileName();
result = UploadImage.uploadImage(fileName, part);
String url = String.valueOf(result.get("url"));
product.setImage(url);
if (result == null) {
throw new RuntimeException("Loi upload");
}
}
dao.update(product);
CodePudding user response:
The Cloudinary upload method supports uploading media files from the sources like a local path, a remote URL, a private storage URL (S3 or Google Cloud storage), a base64 data URI, or an FTP URL.
Based on your code, it seems that you are only supplying the filename of the image.
String fileName = part.getSubmittedFileName();
result = UploadImage.uploadImage(fileName, part);
You would need to update the code to input the local path of the image.