gpt4 book ai didi

java - 如何在 Swift 中将图像上传到 Java 服务器

转载 作者:行者123 更新时间:2023-11-28 09:14:55 25 4
gpt4 key购买 nike

我尝试在 Swift 中将图像上传到 Java 服务器。有一个 Java 代码可以上传图像

public class UploadUtil {
private static final String TAG = "uploadFile";
private static final int TIME_OUT = 10*1000;
private static final String CHARSET = "utf-8";

public String uploadFile(File file,String RequestURL)
{
String result = null;
String BOUNDARY = UUID.randomUUID().toString();
String PREFIX = "--" , LINE_END = "\r\n";
String CONTENT_TYPE = "multipart/form-data";

try {
URL url = new URL(RequestURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(TIME_OUT);
conn.setConnectTimeout(TIME_OUT);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Charset", CHARSET);
conn.setRequestProperty("connection", "keep-alive");
conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY);

if(file!=null)
{
/**
* 当文件不为空,把文件包装并且上传
*/
DataOutputStream dos = new DataOutputStream( conn.getOutputStream());
StringBuffer sb = new StringBuffer();

sb.append(PREFIX);
sb.append(BOUNDARY);
sb.append(LINE_END);

sb.append("Content-Disposition: form-data; name=\"img\"; filename=\""+file.getName()+"\""+LINE_END);
sb.append("Content-Type: application/octet-stream; charset="+CHARSET+LINE_END);
sb.append(LINE_END);
dos.write(sb.toString().getBytes());
InputStream is = new FileInputStream(file);
byte[] bytes = new byte[1024];
int len = 0;
while((len=is.read(bytes))!=-1)
{
dos.write(bytes, 0, len);
}
is.close();
dos.write(LINE_END.getBytes());
byte[] end_data = (PREFIX+BOUNDARY+PREFIX+LINE_END).getBytes();
dos.write(end_data);
dos.flush();
/**
* 获取响应码 200=成功
* 当响应成功,获取响应的流
*/
int res = conn.getResponseCode();
Log.e(TAG, "response code:"+res);
// if(res==200)
// {
Log.e(TAG, "request success");
InputStream input = conn.getInputStream();
StringBuffer sb1= new StringBuffer();
int ss ;
while((ss=input.read())!=-1)
{
sb1.append((char)ss);
}
result = sb1.toString();
Log.e(TAG, "result : "+ result);
// }
// else{
// Log.e(TAG, "request error");
// }
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
}

我需要用 swift 编写代码,但我无法解决这些问题:如何获取文件名?我找不到任何快速获取图片路径的方法。这是我的代码(Swift)

func uploadImageOne(){
var imageData = UIImagePNGRepresentation(imageView.image)

if imageData != nil{
var request = NSMutableURLRequest(URL: NSURL(string:"Enter Your URL")!)
var session = NSURLSession.sharedSession()

request.HTTPMethod = "POST"

var boundary = NSString(format: "---------------------------14737809831466499882746641449")
var contentType = NSString(format: "multipart/form-data; boundary=%@",boundary)
// println("Content Type \(contentType)")
request.addValue(contentType, forHTTPHeaderField: "Content-Type")

var body = NSMutableData.alloc()

// Title
body.appendData(NSString(format: "\r\n--%@\r\n",boundary).dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData(NSString(format:"Content-Disposition: form-data; name=\"title\"\r\n\r\n").dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData("Hello World".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)!)

// Image
body.appendData(NSString(format: "\r\n--%@\r\n", boundary).dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData(NSString(format:"Content-Disposition: form-data; name=\"profile_img\"; filename=\"img.jpg\"\\r\n").dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData(NSString(format: "Content-Type: application/octet-stream\r\n\r\n").dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData(imageData)
body.appendData(NSString(format: "\r\n--%@\r\n", boundary).dataUsingEncoding(NSUTF8StringEncoding)!)



request.HTTPBody = body


var returnData = NSURLConnection.sendSynchronousRequest(request, returningResponse: nil, error: nil)

var returnString = NSString(data: returnData!, encoding: NSUTF8StringEncoding)

println("returnString \(returnString)")

}


}

最佳答案

为了获得图像路径,您必须首先将图像写入指定目录的文件中,而这正是您的代码中缺少的部分。最简单的方法是在用户文档目录中写入:

let fileDirectory = NSSearchPathForDirectoriesInDomains(
.DocumentDirectory, .UserDomainMask, true)

func uploadImageOne(){
var imageData = UIImagePNGRepresentation(imageView.image)

if imageData != nil{
//image path
var imageFilePath = fileDirectory[0].stringByAppendingPathComponent("temp.png")
var imageFileURL = NSURL(fileURLWithPath: imageFilePath)
imageData.writeToURL(imageFileURL!, atomically: false)
...
}
}

在你的图片成功上传后,你可以使用 NSFileManager 删除你的临时文件

var fileManager = NSFileManager.defaultManager()
var error: NSError?
fileManager.removeItemAtPath(path, error: &error)

关于java - 如何在 Swift 中将图像上传到 Java 服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28162471/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com