如何在java中生成签名并在jQuery(Cloudinary)中使用它?

时间:2015-09-28 07:15:36

标签: java jquery cloudinary

我正在尝试使用jQuery和Java将图像上传到Cloudinary。我尝试了link中的代码而没有运气。我在生成签名时遇到错误。 有没有人有一个生成签名的工作实现的例子?那会更有帮助。

2 个答案:

答案 0 :(得分:1)

将以下代码放在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>

如果你有一个maven项目,那么将这些依赖项放在你的pom.xml中,或者下载他们的jar并将它们放在你的&#39; lib&#39;文件夹中。

<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>

最后创建一个Servlet:

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 = "&quot;api_key&quot;:&quot;874837483274837&quot;,&quot;timestamp&quot;:&quot;" + unixTime + "&quot;";
        String unsignedDataForSHA = "timestamp="+unixTime;
        String apiSecret = "-----place your api secret here-----";
        String unsignedDataSecret = unsignedDataForSHA + apiSecret;
        String signedData = unsignedData + ",&quot;signature&quot;:&quot;" + DigestUtils.shaHex(unsignedDataSecret.getBytes()) + "&quot";

        JSONObject jsonObject = new JSONObject("{" + signedData.replaceAll("&quot;", "\"") + "}");

        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);
    }
}

请记住:替换Cloudinary控制台主页中给出的api-key,cloud-name和api-secret。此外,您可能需要更改index.jsp中的.js文件的位置。

答案 1 :(得分:0)

虽然非常感谢Asim的回答,但请注意Cloudinary的Java SDK已经提供了一种帮助方法来为您生成签名。简单地通过参数,你就完成了。 请参阅以下内容以供参考: https://github.com/cloudinary/cloudinary_java/blob/master/cloudinary-core/src/main/java/com/cloudinary/Cloudinary.java#L133