我想从java

时间:2016-01-27 13:51:15

标签: java xml api rest

我在java中有REST API,它采用图像文件并保存在服务器上我想以XML格式返回上传图像的路径,但不知道如何操作。目前它以字符串形式返回响应浏览器。

这是我的代码。

package com.javacodegeeks.enterprise.rest.jersey;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import com.sun.jersey.core.header.FormDataContentDisposition;
import com.sun.jersey.multipart.FormDataParam;

@Path("/files")
public class JerseyFileUpload {

    private static final String SERVER_UPLOAD_LOCATION_FOLDER = "/home/hassan/Downloads/";

    /**
     * Upload a File
     */

    @POST
    @Path("/upload")
    @Consumes(MediaType.MULTIPART_FORM_DATA)
    public Response uploadFile(
            @FormDataParam("file") InputStream fileInputStream,
            @FormDataParam("file") FormDataContentDisposition contentDispositionHeader) {

        String filePath = SERVER_UPLOAD_LOCATION_FOLDER + contentDispositionHeader.getFileName();

        // save the file to the server
        saveFile(fileInputStream, filePath);

        String output = "File saved to server location : " + filePath;

        return Response.status(200).entity(output).build();

    }

    // save uploaded file to a defined location on the server
    private void saveFile(InputStream uploadedInputStream,
            String serverLocation) {

        try {
            OutputStream outpuStream = new FileOutputStream(new File(serverLocation));
            int read = 0;
            byte[] bytes = new byte[1024];

            outpuStream = new FileOutputStream(new File(serverLocation));
            while ((read = uploadedInputStream.read(bytes)) != -1) {
                outpuStream.write(bytes, 0, read);
            }
            outpuStream.flush();
            outpuStream.close();
        } catch (IOException e) {

            e.printStackTrace();
        }

    }

}

1 个答案:

答案 0 :(得分:3)

如果要从Rest返回xml,请尝试使用某些字段创建Object。对象和字段将包含@XmlRootElement @XmlElement并将@Produces(" application / xml")置于方法签名之上。

    @POST
    @Path("/upload")
    @Consumes(MediaType.MULTIPART_FORM_DATA)
    @Produces("application/xml")
    public Response uploadFile(...){
         //body
   }

您也可以使用@produces(MediaType.APPLICATION_XML)代替@Produces("application/xml")。两者都是一样的。