I'm trying to upload images to Cloudinary using jQuery and Java. I tried the code in this link with no luck. I'm getting errors in generating the signature. Does anyone have an example of a working implementation for generating the signature? That would be more helpful.
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
Place the following code in your index.jsp:
<html>
<head>
<title></title>
<script src='jquery.min.js' type='text/javascript'></script>
<script src='jquery.ui.widget.js' type='text/javascript'></script>
<script src='jquery.iframe-transport.js' type='text/javascript'></script>
<script src='jquery.fileupload.js' type='text/javascript'></script>
<script src='jquery.cloudinary.js' type='text/javascript'></script>
<script type = "text/javascript">
$.cloudinary.config({ cloud_name: 'sample', api_key: '874837483274837'});
</script>
</head>
<body>
<input name="file" type="file"
class="cloudinary-fileupload" data-cloudinary-field="image_id"
data-form-data="${signedData}" />
</body>
</html>
If you have a maven project then place these dependencies in your pom.xml or else download their jars and place them in your 'lib' folder.
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20090211</version>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.4</version>
</dependency>
Finally create a Servlet as:
import org.apache.commons.codec.digest.DigestUtils;
import org.json.JSONObject;
public class SignRequestServlet extends HttpServlet{
public void doGet(HttpServletRequet request, HttpServletResponse response) throws ServletException, IOException{
long unixTime = System.currentTimeMillis() / 1000L;
String unsignedData = ""api_key":"874837483274837","timestamp":"" + unixTime + """;
String unsignedDataForSHA = "timestamp="+unixTime;
String apiSecret = "-----place your api secret here-----";
String unsignedDataSecret = unsignedDataForSHA + apiSecret;
String signedData = unsignedData + ","signature":"" + DigestUtils.shaHex(unsignedDataSecret.getBytes()) + """;
JSONObject jsonObject = new JSONObject("{" + signedData.replaceAll(""", "\"") + "}");
request.setAttribute("signedData", jsonObject.toString());
request.getRequestDispatcher("/index.jsp").forward(request,response);
}
public void doPost(HttpServletRequet request, HttpServletResponse response) throws ServletException, IOException{
doGet(request, response);
}
}
Remember: Replace the api-key, cloud-name and api-secret as given in the home page of Cloudinary console. Also, you may need to change the location of the .js files in index.jsp.
回答2:
While Asim's answer is very appreciated, also note that Cloudinary's Java SDK already offers a helper method to generate the signature for you. Simply pass the params and you're done. See the following for reference: https://github.com/cloudinary/cloudinary_java/blob/master/cloudinary-core/src/main/java/com/cloudinary/Cloudinary.java#L133