spring上傳圖片

import java.io.BufferedOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

@Controller
public class UploadImageController {

            @RequestMapping(value = "/uplaod", method = RequestMethod.POST)
            public @ResponseBody
            String uploadImage(@RequestParam("name") String name, @RequestParam("file") MultipartFile file) {
                        if (!file.isEmpty()) {
                                    try {
                                                byte[] bytes = file.getBytes();
                                                java.io.BufferedOutputStream stream = new BufferedOutputStream(
                                                        new java.io.FileOutputStream(
                                                                new java.io.File(name + "-upload")));
                                                stream.write(bytes);
                                                stream.close();
                                                return "you successfully uploaded " + name + " into " + name + "-upload";
                                    } catch (FileNotFoundException ex) {
                                                return "you failed to upload " + name + "==>" + ex.getMessage();
                                    } catch (IOException ex) {
                                                return "you failed to upload " + name + "==>" + ex.getMessage();
                                    }
                        } else {
                                    return "your failed to uplaod " + name + " because the file is empty";
                        }
            }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章