我正在尝试使用jQuery和Java将图像上传到Cloudinary。我没有运气就尝试过link中的代码。生成签名时出现错误。
有人有生成签名的有效实现示例吗?那会更有帮助。
最佳答案
将以下代码放入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并将其放在“ lib”文件夹中。
<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 = ""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);
}
}
切记:替换Cloudinary控制台主页中提供的api-key,cloud-name和api-secret。另外,您可能需要更改index.jsp中.js文件的位置。