2015-05-29 119 views
-1

我正在建设项目与春季启动,我想上传图像到服务器(在我的本地服务器上)。如何将图片上传到服务器?

代码上传的文件是:

@Controller 
@RequestMapping("/api/v1") 
public class ImageController { 

    @RequestMapping(value="/upload", method=RequestMethod.GET) 
    public @ResponseBody String provideUploadInfo() { 
     return "You can upload a file by posting to this same URL."; 
    } 

    @RequestMapping(value="/upload", method=RequestMethod.POST) 
    public @ResponseBody String handleFileUpload(@RequestParam("name") String name,@RequestParam("email") String email, 
      @RequestParam("file") MultipartFile file){ 
     if (!file.isEmpty()) { 
      BufferedImage src; 
      try { 
       src = ImageIO.read(new ByteArrayInputStream(file.getBytes())); 
      File destination = new File("/"+System.getProperty("user.home")+"/samepinchbucket/"+email+"/pics/"); 
       ImageIO.write(src, "png", destination); 
      //Save the id you have used to create the file name in the DB. You can retrieve the image in future with the ID. 
      return "You successfully uploaded " + name + "!"; 
      } catch (IOException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
       return "You failed to upload " + name + " => " + e.getMessage(); 
      } 
      }else{ 
       return "You failed to upload " + name + " because the file was empty."; 
      } 
    } 

} 

此代码工作正常,但图像在myfolder正在上传与pics为图像的名字,但我的需求量的是,图像应pics文件夹内的email folder上传不。

回答

1

您应该简单地使用不同的File构造函数,例如,

String folder = "/"+System.getProperty("user.home")+ "/samepinchbucket/"+email+"/pics/"; 
File destination = new File(folder, file.getOriginalFilename()); 

这将一个文件夹里面pics存储文件的原始文件名

0

从您的代码下,看来你正在使用Spring中的一些Java的Web服务器。

假设getImageDirPath()方法返回imagePath相对于Tomcat服务器的主目录:

private static String getImageDirPath(String email) { 
    String envVal = null; 
    String rootPath = System.getProperty("catalina.home"); 
    File dir = new File(rootPath + File.separator + "samepinchbucket" + File.separator + 
         email+File.separator + "pics" + File.separator); 
    if (!dir.exists()) 
     dir.mkdirs(); 
    return dir.getAbsolutePath() + File.separator; 
} 

参考:http://www.proactiveclass.com/tutorials/java/spring/image-upload-android-app-using-spring-tomcat-server