我写了一些代码,想测试一个上传图片功能(尝试将我的iPhone上的图片上传到Mac)
我使用Alamofire4在Xcode8中上传图像,然后创建一个javaWeb来接收Serlvet的图像。
我认为测试后我在Mac上收到了图像的数据,但我无法打开图像。我知道我没有解析DATA(Alamofire4创建的MultipartFormData)。
所以,这是我的问题:如何在Serlvet中解析这个数据来显示真实的图像而不是我的Mac中的imageData 我认为这对javaWeb开发人员来说太容易了,但对我来说很难 请告诉我修改。
这是使用Alamofire4的快速代码:
@IBAction func chooseImage(_ sender: UIButton) {
var picker : UIImagePickerController
picker = UIImagePickerController()
picker.delegate = self
picker.sourceType = UIImagePickerControllerSourceType.photoLibrary
self.present(picker, animated: true, completion: nil)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
myImage.image = info[UIImagePickerControllerOriginalImage] as! UIImage?
self.dismiss(animated: true, completion: nil)
}
@IBAction func uploadData(_ sender: UIButton) {
let imageData = UIImageJPEGRepresentation(myImage.image!, 1)
imageRename = myText.text!+".jpeg"
Alamofire.upload(multipartFormData:{(multiData) in
multiData.append(imageData!, withName: "imageMine", fileName: self.imageRename!, mimeType: "image/*")},
usingThreshold:UInt64.init(),
to:"http://192.168.0.101:8080/John_SImage/imageServlet",
method:.post,
headers:nil,
encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.responseJSON { response in
debugPrint(response)
}
case .failure(let encodingError):
print(encodingError)
}
})
}
以下是Servlet(javaWeb)中的代码:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("1111");
request.setCharacterEncoding("UTF-8");
response.setContentType("text/plain;charset=utf-8");
PrintWriter writer=response.getWriter();
InputStream in=request.getInputStream();
File f = new File("/Users/BC/Desktop/ff.jpeg");
FileOutputStream fout = new FileOutputStream(f);
byte[] b=new byte[1024];
int n=0;
while ((n=in.read(b))!=-1){
fout.write(b,0,n);
}
fout.close();
in.close();
writer.println("Finished uploading files!");
writer.close();
}